JavaFX: data transfer between controllers is always zero

I want to apologize in advance as this is discussed earlier in Passing Parameters Directly from Caller to Controller , but I've followed every possible solution I found and yet I can't get it to work.

I find it difficult to pass a parameter from one controller to another.

In particular:

LoginController passes username

to MainController .

When the login button is clicked, the LoginController sets username

to the MainController . But Main.fxml username

is NULL when loaded .

As I try to figure it out, I would like to ask:

  • When is the MainController method calledinitialize()

    ? I suppose by the time the LoginController calls st.show();

    ?
  • If the previous is correct, then why is the MainController username

    NULL since we have already set its value in the 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);
        ...
    }
    ...
}

      

+3


source to share


1 answer


The problem is the urgency of your call for installation username

.

The method initialize()

MainController

is called during the execution of the following statement:

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

      



At this time, the field username

in MainController

equal null, so its value is reported in the message of welcome as the null. Your call setUsername()

occurs after the method completes MainController.initialize()

.

In general, the method initialize()

of controller classes loaded by the FXML loader should never try to do anything with instance fields whose values ​​were not supplied by the FXML loader. These field instances will not be initialized when the method is called initialize()

.

+1


source







All Articles