JavaFX - 如何获得 FXML 控制器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25828561/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaFX - How to get FXML Controller?
提问by ceklock
I have the following code:
我有以下代码:
Parent parent = FXMLLoader.load(Main.class.getResource("JanelaPrincipal.fxml"));
in the fxml file there is a reference to the controller class. How can I get the controller object?
在 fxml 文件中有对控制器类的引用。如何获取控制器对象?
fxml:
文件:
<AnchorPane id="AnchorPane" fx:id="root"
prefHeight="768.0" prefWidth="1024.0" xmlns:fx="http://javafx.com/fxml/1"
xmlns="http://javafx.com/javafx/2.2"
fx:controller="br.meuspila.javafx.JanelaPrincipalController">
...
采纳答案by jewelsea
Instantiate an FXMLLoader and use an instance load method rather than a class static load method. You can then retrieve the controller instance from the loader instance.
实例化 FXMLLoader 并使用实例加载方法而不是类静态加载方法。然后,您可以从加载程序实例中检索控制器实例。
FXMLLoader loader = new FXMLLoader(
getClass().getResource(
"customerDialog.fxml"
)
);
Pane pane = (Pane) loader.load();
CustomerDialogController controller =
loader.<CustomerDialogController>getController();
controller.initData(customer);
For more info see:
有关更多信息,请参阅: