问题描述
我想从我加载FXMLoader的场景中获取控制器。用例是:
I want to get the controller from a scene that i've loaded with FXMLoader. The use case is:
- 我的JSON管理器收到一个JSON对象
-
任务我推出了一个新的场景,使用
- My JSON manager receives a JSON object
The task I've launched shows a new Scene using
Parent p = FXMLLoader.load(getClass().getResource("foo.fxml"));
Scene scene = new Scene(p);
stage.setScene(scene);
之后,我有空场景。
现在我这样做来填充组件
Now I do this to fill the components
AnchorPane pane = (AnchorPane)((AnchorPane) scene.getRoot()).getChildren().get(0);
for(Node node : pane.getChildren()){
String id = node.getId();
if(id.equals(NAME)){
((TextField)node).setText(value);
}
}
我的问题是,有更简单的方法吗?我在FXML中指定了一个控制器
My question, is there an easier way to do this? I have a controller specified in FXML
<AnchorPane id="AnchorPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="526.0" minWidth="356.0" prefHeight="526.0" prefWidth="356.0"
xmlns:fx="http://javafx.com/fxml" fx:controller="bar.foo">
我想用绑定值获取实例(在这种情况下,TextField名为name)
I want to get the instance with the bind values (TextField called name in this case)
提前致谢
推荐答案
1)你可以从 FXMLLoader 但不知道是否可以从场景
:
1) You can get the controller from the FXMLLoader
but don't know is it possible from Scene
:
FXMLLoader fxmlLoader = new FXMLLoader();
Pane p = fxmlLoader.load(getClass().getResource("foo.fxml").openStream());
bar.foo fooController = (bar.foo) fxmlLoader.getController();
稍后使用 fooController
部分代码,您可以使用 Node#setUserData()
。例如,在上面的代码之后:
To use the fooController
later in a different part of your code, you can use Node#setUserData()
. For example after the code above:
p.setUserData(fooController);
...
// after a while of app logic and code
bar.foo controller_of_p = (bar.foo) p.getUserData();
这提供了一种解决方法和实现目标的快捷方式。
This gives a workaround and a shortcut to achieve your goal.
2)如果你的节点有一个id,你可以直接 Node#lookup()
而不是构造一个for循环:
2) If your node has an id then you can directly Node#lookup()
it rather than constructing a for-loop :
TextField txt = (TextField) pane.lookup("#nodeId");
这篇关于JavaFX 2.0 + FXML。从其他任务更新场景值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!