Issue
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?
Solution
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.
Answered By - mipa