JavaFX控制器始终为null [英] JavaFX controller is always null
问题描述
我将尝试使用JavaFX 2并使用一个简单的演示应用程序。
项目包含3个文件,Main.java,Controller.java和sample.fxml。
I'll try to get in JavaFX 2 and used a simple demo app. The Project consists of 3 Files, the Main.java, the Controller.java and the sample.fxml.
在Sample.fxml中,我声明了控制器:
In Sample.fxml i declared the controller:
<GridPane fx:controller="sample.Controller"
xmlns:fx="http://javafx.com/fxml" alignment="center" hgap="10" vgap="10">
</GridPane>
在我的Main.java中,我尝试访问控制器
And in my Main.java I try to access the controller
FXMLLoader loader = new FXMLLoader();
Parent root = loader.load(getClass().getResource("sample.fxml"));
System.out.println(loader.getController()); //prints always null
所以我的第一个想法是映射不起作用。所以我在控制器中添加了一个初始化方法。
So my first idea was that the mapping doesn't work. So I added a initialize method in the controller.
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
System.out.println("init");
}
输出现在是:
init
init
null
所以现在我的问题是如何访问给定fxml文件的控制器?
So my Question now is how can i access the controller of a given fxml file?
推荐答案
FXMLLoader.load(URL)
方法是一种静态方法。所以当你执行
The FXMLLoader.load(URL)
method is a static method. So when you execute
FXMLLoader loader = new FXMLLoader();
Parent root = loader.load(getClass().getResource("sample.fxml"));
您没有从您构建的FXMLLoader实例(loader)加载FXML文件。 (您实际上是通过对象引用调用静态方法。)因此,加载器的控制器永远不会被初始化。
you are not loading the FXML file from the instance of the FXMLLoader that you constructed ("loader"). (You're actually invoking the static method through an object reference.) Hence the loader's controller never gets initialized.
您需要
FXMLLoader loader = new FXMLLoader(getClass().getResource("sample.fxml"));
Parent root = loader.load();
这构造了一个带有指定位置的加载器,然后是 load()在FXMLLoader实例上正确调用
方法,它不是静态方法。然后
This constructs a loader with a location specified, and then the load()
method, which is not a static method, is properly invoked on the FXMLLoader instance. Then
System.out.println(loader.getController());
将给出正确的结果。
这篇关于JavaFX控制器始终为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!