如何获取对我的 Controller 类的引用?
这是我的代码片段。
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 属性中指定。该实例在后台自动创建。我需要访问该实例才能在表单中设置初始值。
我知道我可以在 XML 中设置初始值,但我需要在运行时设置它们。
最佳答案
不要使用静态 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));
关于JavaFX - 如何获取 Controller 对象的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34457811/