Passing parameters to a controller when loading an FXML [duplicate]
After loading the controller with the FXMLLoader, it is possible to call for members of said controller before the show() method is invoked. One must get the reference to the controller just invoked and call a set() method from there (or access the attribute directly, if defined public).
From the example, let us suppose that the controller associated with Main.fxml is called MainController, and MainController has a userId attribute, defined as an int. Its set method is setUser(int user). So, from the LoginController class:
LoginController.java:
// User ID acquired from a textbox called txtUserId
int userId = Integer.parseInt(this.txtUserId.getText());
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("fxml/Main.fxml"));
Parent root = (Parent)fxmlLoader.load();
MainController controller = fxmlLoader.<MainController>getController();
controller.setUser(userId);
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
MainController.java:
public void setUser(int userId){
this.userId = userId;
}
MainController.java:
//You may need this also if you're getting null
@FXML private void initialize() {
Platform.runLater(() -> {
//do stuff
});
}