java JavaFX - 如何获取控制器对象的实例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34457811/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 22:55:04  来源:igfitidea点击:

JavaFX - how to get instance of the controller object

javajavafx

提问by user3523268

How do I get a reference to my controller class?

如何获得对我的控制器类的引用?

Here is my code snippet.

这是我的代码片段。

Parent root = FXMLLoader.load(getClass().getResource("my.fxml"));
stage.setScene(new Scene(root, 500, 500));
MyController c = stage.getControllerInstance(); <-- HOW???
c.setATextValue("Hello world"); //Set initial value
stage.show();

The Controller class is specified in FXML in the fx:controllerattribute. The instance gets created automatically in the background. I need access to that instance in order to set initial values in the form.

Controller 类在 FXML 中的fx:controller属性中指定。实例在后台自动创建。我需要访问该实例才能在表单中设置初始值。

I know I can set the initial values in XML, but I need to set them at runtime.

我知道我可以在 XML 中设置初始值,但我需要在运行时设置它们。

回答by James_D

Don't use the static FXMLLoader.load(...)method. Instead, create an FXMLLoaderinstance and call load()on the instance. Then you can call getController():

不要使用静态FXMLLoader.load(...)方法。相反,创建一个FXMLLoader实例并调用load()该实例。然后你可以打电话getController()

FXMLLoader loader = new FXMLLoader(getClass().getResource("my.fxml"));
Parent root = loader.load();
MyController c = loader.getController();

stage.setScene(new Scene(root, 500, 500));