All JavaFX FXML objects null in controller

為{幸葍}努か 提交于 2019-12-02 06:16:47

A call to SettingsPage.init results in

root = FXMLLoader.load(file.toURI().toURL());

creating a new instance of SettingsPage. FXMLLoader automatically uses the constructor not taking parameters to create a controller instance, if the fx:controller attribute is present in the fxml. Objects in the fxml are injected to this new instance. However GetPrizesThread uses the old SettingsPage instance.

You can fix this by passing the controller to FXMLLoader before loading the fxml:

FXMLLoader loader = new FXMLLoader(file.toURI().toURL());
loader.setController(this);
root = loader.load();

You need to remove the fx:controller attribute from the fxml for this to work.


There's a different issue in your code however:

The GUI must not be accessed by threads other than the JavaFX application thread, but GetPrizesThread runs on a different thread. You need to do the GUI updates using Platform.runLater (or via some other mechanism resulting in updates running on the application thread):

@Override
public void receivePrizes(ArrayList<String> prizes) {
    // do update on the javafx application thread
    Platform.runLater(() -> {
        prizeList.getItems().addAll(prizes);
    });
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!