25
votes

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?

1
stackoverflow.com/questions/13003323/javafx-how-to-change-stage/… , example mentioned in that answer has what you need :)invariant
I'm getting lost in your example... Sergey posted this example: stackoverflow.com/questions/10134856/… But I cant seem to get the reference to the previous controller when I load up the new controller.Dynelight
logic in that example is , having user data in App(main java class which extends Application) class and then accessing data in all controllers. if its still not clear let me know :)invariant
Also I cant get the code from that link, seems broken...Dynelight
go to the bottom of this page :) oracle.com/technetwork/java/javase/downloads/…invariant

1 Answers

48
votes

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

    });
        
}