title: JavaFX: passing data between Controllers is always null
body: <p>I want to apologize in advance, as this is discussed previously in <a href="https://stackoverflow.com/questions/14187963/passing-parameters-javafx-fxml">"Passing Parameters Directly From the Caller to the Controller"</a>, but I followed every possible solution I found and still I can't get it work.</p>
  
  <p>I have difficulty in passing a parameter  from one controller to another.</p>
  
  <p>Specifically:</p>
  
  <p><strong>LoginController</strong> passes <code>username</code> to <strong>MainController</strong>.</p>
  
  <p>When I click login button <strong>LoginController</strong> sets the <code>username</code> to the <strong>MainController</strong>. But, when Main.fxml is loaded <code>username</code> is NULL.</p>
  
  <p>As trying to figure it out, I would like to ask:</p>
  
  <ol>
  <li>When <strong>MainController</strong> <code>initialize()</code> method gets called? I suppose by the time <strong>LoginController</strong> calls <code>st.show();</code> ?</li>
  <li>If the previous is correct, then why <strong>MainController</strong> <code>username</code> is NULL, since we have already set its value in <strong>LoginController</strong> using <code>mainController.setUsername(username)</code> ?</li>
  </ol>
  
  <p>Any help would be appreciated.</p>
  
  <p>This is my code.</p>
  
  <p><strong>LoginController.java</strong></p>
  
  <pre><code>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.&lt;MainController&gt;getController();
          mainController.setUsername(username.getText());
  
          st.show();
      }
      ...
  }
  </code></pre>
  
  <p><strong>MainController.java</strong></p>
  
  <pre><code>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);
          ...
      }
      ...
  }
  </code></pre>