Passing parameters to a controller when loading an FXML

Dynelight picture Dynelight · Jan 17, 2013 · Viewed 55.9k times · Source

I have a login screen, and I want to pass the login ID from the LoginController to the MainController, so I can access some functions to change password and whatnot.

I load the controller like this:

FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("fxml/Main.fxml"));     

Parent root = (Parent)fxmlLoader.load();          
Scene scene = new Scene(root); 

stage.setScene(scene);    

stage.show();   

Main.fxml is bounded to the MainController.java. Is there a way I can pass the user ID I need, and access it on the initialize() method of the controller?

Answer

Dynelight picture Dynelight · Jan 21, 2013

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

    });
        
}