I want to apologize in advance, as this is discussed previously in "Passing Parameters Directly From the Caller to the Controller", but I followed every possible solution I found and still I can't get it work.
I have difficulty in passing a parameter from one controller to another.
Specifically:
LoginController passes username to MainController.
When I click login button LoginController sets the username to the MainController. But, when Main.fxml is loaded username is NULL.
As trying to figure it out, I would like to ask:
- When MainController initialize()method gets called? I suppose by the time LoginController callsst.show();?
- If the previous is correct, then why MainController usernameis NULL, since we have already set its value in LoginController usingmainController.setUsername(username)?
Any help would be appreciated.
This is my code.
LoginController.java
public class LoginController implements Initializable {
    ...
    @FXML TextField username;
    @FXML public void actionLoginButton() {
        ...
        Stage st = new Stage();
        FXMLLoader loader = new FXMLLoader(getClass().getResource("Main.fxml"));
        Region root = (Region) loader.load();
        Scene scene = new Scene(root);
        st.setScene(scene);
        MainController mainController = loader.<MainController>getController();
        mainController.setUsername(username.getText());
        st.show();
    }
    ...
}
MainController.java
public class MainController implements Initializable {
    ...
    String username;
    @FXML Label lblWelcomeUser;
    public void setUsername(String usrname) {
        this.username = usrname;
    }
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        ...    
        lblWelcomeUser.setText("Welcome, " + this.username);
        ...
    }
    ...
}
 
     
    