JavaFX - 如何获取控制器对象的实例 [英] JavaFX - how to get instance of the controller object

查看:649
本文介绍了JavaFX - 如何获取控制器对象的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I get a reference to my controller class?

这是我的代码片段。

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();

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

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

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

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

推荐答案

不要使用静态 FXMLLoader.load(...)方法。而是在实例上创建一个 FXMLLoader 实例并调用 load()。然后你可以调用 getController()

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

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

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

这篇关于JavaFX - 如何获取控制器对象的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆