I was learning JavaFX this days and I got stuck on this error here:
I'm creating a simple game, like Tribal Wars / Clash of Clans. My question here is about how I can send information from one stage (window / confirmSerra.fxml / Controller2.java) to another stage (primarystage / aldeiaPage.fxml / aldeiaControl.java) that is already created and running.
I already know how to send information from one stage to another if it's not created yet.
This is my Main.java that starts the principalStage
of the game:
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(getClass().getResource("aldeiaPage.fxml"));
Parent root = fxmlLoader.load();
primaryStage.setTitle("Jogo_Alpha - Aldeia");
primaryStage.setScene(new Scene(root, 1024, 768));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
This is some part of the controller "aldeiaControl.java" from the "aldeiaPage.fxml":
@FXML public void teste1() throws Exception {
Stage window = new Stage();
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(getClass().getResource("confirmSerra.fxml"));
Pane layout = fxmlLoader.load();
Scene scene = new Scene(layout);
Controller2 c = fxmlLoader.getController();
window.setTitle("Upgrade Serralheria");
window.setScene(scene);
window.show();
c.labelserraLev.setText(String.valueOf(seralevelNum));
//seralevelNum is a variable from this controller "aldeiaControl"
}
As you can see, I can create a new stage from the button click teste1, that is linked to the @FXML file. And making this FXMLLoader
and .getController()
give me acess to the labelserraLev
that is in the other controller.
Controller2.java
public class Controller2 {
@FXML public Label labelserraLev;
@FXML public void buttonclick() throws Exception {
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.load(getClass().getResource("aldeiaPage.fxml"));
aldeiaControl labelchange = fxmlLoader.getController();
labelchange.seralevel.setText("10");
}
}
How can I change the label text of the principalstage
(that was already created and is still running), when I click this buttonclick()
(that is the Upgrade button in the photo below)? I could change the label text of the new window, but because it was a new window, but about a window that is already created, I can't.
The error is this:
Caused by: java.lang.NullPointerException
at sample.Controller2.buttonclick(Controller2.java:30)