Issue
There is an possibility to get Controller instance from Node ?? for example AnchorPane on Tab ?
I have some AnchorPanes where I load different Controllers and I would like to verify which controller is already loaded
Solution
Node
s do not contain any information about a controller used with the fxml file used to create it by default, since fxml is just one way of creating a scene. However you could attach information like this to the userData
/properties
in the fxml:
<AnchorPane xmlns:fx="http://javafx.com/fxml/1" fx:id="AnchorPane" prefHeight="400.0" prefWidth="600.0" onMouseClicked="#click" fx:controller="fxml.FXMLController">
<!-- store controller as userData property -->
<userData>
<fx:reference source="controller" />
</userData>
<properties>
<!-- store controller at key "foo" in properties map -->
<foo><fx:reference source="controller" /></foo>
</properties>
</AnchorPane>
If you do this, you can lookup the controller at closest ancestor of a node where you added this kind of information using
public static Object getController(Node node) {
Object controller = null;
do {
controller = node.getProperties().get("foo");
node = node.getParent();
} while (controller == null && node != null);
return controller;
}
to retrieve the info from the properties
map or using
public static Object getController(Node node) {
Object controller = null;
do {
controller = node.getUserData();
node = node.getParent();
} while (controller == null && node != null);
return controller;
}
to retrieve the info from the userData
property.
You should probably use just one way of adding the info though, not both. Also it would be better to replace foo
as key...
Answered By - fabian
Answer Checked By - David Marino (JavaFixing Volunteer)