有可能从Node获取Controller实例吗?例如Tab上的AnchorPane?
我有一些AnchorPanes,我加载不同的控制器,我想验证哪个控制器已经加载
Nodes不包含任何与默认情况下用于创建它的fxml文件一起使用的控制器的信息,因为fxml只是创建场景的一种方法.但是你可以将这样的信息附加到fxml中的userData/ properties:
<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>
Run Code Online (Sandbox Code Playgroud)
如果执行此操作,则可以使用添加此类信息的节点的最近祖先查找控制器
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;
}
Run Code Online (Sandbox Code Playgroud)
从properties地图中检索信息或使用
public static Object getController(Node node) {
Object controller = null;
do {
controller = node.getUserData();
node = node.getParent();
} while (controller == null && node != null);
return controller;
}
Run Code Online (Sandbox Code Playgroud)
从userData属性中检索信息.
您应该只使用一种方式添加信息,而不是两者.也可以更换foo为关键...
| 归档时间: |
|
| 查看次数: |
3770 次 |
| 最近记录: |