1

My program has two scenes, firstScene.fxml and secondScene.fxml, each with corresponding Controller classes FirstController.java and SecondController.java.

I want to be able to use Stage's getUserData() on my SecondController class, after it has been loaded on the FirstController class using the onAction event of a Button, and an FXMLLoader.

This is a snippet of my code on the SecondController class:

    @FXML
    public void initialize() throws IOException {
        Stage window = (Stage) statusLabel.getScene().getWindow();
        statusLabel.setText("" + window.getUserData());
    }

getUserData() is based from my setUserData(message) on my FirstController class, where the value of message is a String.

This however outputs an error:

Caused by: java.lang.NullPointerException: Cannot invoke "javafx.scene.Scene.getWindow()" because the return value of "javafx.scene.control.Label.getScene()" is null

How do I then use getUserData() on my SecondController class right after it has been loaded by my FirstController class?

noodles888
  • 31
  • 5
  • When initialize is called the elements created by the fxml loader aren’t yet in a scene. That won’t happen until whatever loaded the fxml adds the resultant node from the loader into a scene. Then you could get the controller and call a method on it [like this](https://stackoverflow.com/questions/14187963/passing-parameters-javafx-fxml) and then do your work where you extract the user data you previously stored in the stage. But that would all be weird and convoluted. Mipa’s recommended approach or the mvc approach mentioned in the answer I linked is superior. – jewelsea Oct 23 '21 at 10:41
  • @jewelsea Thanks for that info! Will read about it. – noodles888 Oct 23 '21 at 11:20

1 Answers1

1

All your GUI code should work with a common model. If you'd do that there is no need for controllers to talk with each other because they can all access the common model. Google vor MVVM to find some tutorial on this important aspect of any GUI programming.

mipa
  • 10,369
  • 2
  • 16
  • 35