my imageI\'m trying to pass the data (variables) from one stage to another stage, but when I try to access them in the second stage they are null. Code of the mainWindow. Go to
The initialize()
method is called as part of the process of loading the FXML file - in other words it is called when you call miCargador.load()
.
Obviously this happens before you call window1.initStage(...)
, so when initialize()
is invoked, tituloAnterior
is still null.
The simple solution is just not to access tituloAnterior
in the initialize()
method, but to do whatever you need to do with it in the initStage()
method. E.g.
public void initStage(Stage stage){
primaryStage = stage;
escenaAnterior = stage.getScene();
tituloAnterior = stage.getTitle();
primaryStage.setTitle("Window 1");
someLabelFromFXML.setText(tituloAnterior);
}
If you prefer, you could set the controller for the FXML loader in the Java code:
@FXML
private void goWindow1(ActionEvent event) {
try {
FXMLLoader miCargador = new
FXMLLoader(getClass().getResource("/vista/Window1.fxml"));
Window1Controller window1 = new Window1Controller();
window1.initStage(primaryStage);
miCargador.setController(window1);
Parent root = (Parent) miCargador.load();
// Access to window driver 1
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
} catch (IOException e) {e.printStackTrace();}
}
}
Then remove the fx:controller
attribute from your FXML file. This way the initStage()
method is called before the load()
method, and tituloAnterior
will not be null when initialize()
is called.