John Astralidis
John Astralidis

Reputation: 367

JavaFX: passing data between Controllers is always null

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:

  1. When MainController initialize() method gets called? I suppose by the time LoginController calls st.show(); ?
  2. If the previous is correct, then why MainController username is NULL, since we have already set its value in LoginController using mainController.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);
        ...
    }
    ...
}

Upvotes: 3

Views: 13684

Answers (1)

scottb
scottb

Reputation: 10084

The issue is the timing of your call to set username.

The initialize() method of MainController is called during the execution of the following statement:

Region root = (Region) loader.load();

At this time, the username field in MainController is null and so its value is reported as null in the welcome message. Your call to setUsername() occurs after the MainController.initialize() method has completed.

In general, the initialize() method of controller classes loaded with the FXML loader should never try to do anything with instance fields whose values have not been injected by the FXML loader. These instance fields will not have been initialized at the time that the initialize() method is invoked.

Upvotes: 5

Related Questions