All JavaFX FXML objects null in controller

后端 未结 1 468
小蘑菇
小蘑菇 2021-01-23 14:40

I realise that this question has been asked before but none of the solutions have worked for me. I am starting a thread from my controller, and from there the thread gets some d

相关标签:
1条回答
  • 2021-01-23 15:30

    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);
        });
    }
    
    0 讨论(0)
提交回复
热议问题