JavaFx-when fxml inject object field?

拟墨画扇 提交于 2020-01-22 02:50:11

问题


I'm new to javaFx,and I have found only within the @fxml function and initialize function the @fxml field not be null otherwise the @fxml field will always be null,is it true? If so,how can i use a @fxml field immediately after i load a fxml(do not use lookup),just like this?(the code follow will throw a null exception)

    @FXML Label resultTF;
    ....
    FXMLLoader loader=new FXMLLoader();
    loader.setController(this);

    Parent pane = loader.load(getClass().getResource("/fxml/Main.fxml"));
    this.resultTF.setText("");

All i want to do is to declare a field with id in the fxml,and use it immediately after load the fxml,something like wpf,flex


回答1:


You are calling the static FXMLLoader.load(URL) method.

Since it's a static method, it knows nothing about the instance you are using to invoke it (which is bad practice anyway; your IDE should issue a warning about this). Specifically, it doesn't have a controller set.

You need to invoke an instance load() method, e.g.

FXMLLoader loader=new FXMLLoader();
loader.setController(this);
loader.setLocation(getClass().getResource("/fxml/Main.fxml"));

Parent pane = loader.load();



回答2:


You can specify the controller in the FXML file. The FXMLLoader will initialize the variables in the controller. In that case there is not problem with your code. It is good practice to separate the controller from the main class.



来源:https://stackoverflow.com/questions/46650444/javafx-when-fxml-inject-object-field

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!