title: How can I fix a NullPointerException when interacting with FXML elements in the start method?
body: <p>I'm writing some code where I interact (Change text) with FXML elements from the start method. However, I find that when I call the method from my controller class I get a NullPointerException. I've found that the issue has something to do with threads, but I have been able to get anything to work. I have included some sample code that generates the same problem.</p>
  
  <p>Main class:</p>
  
  <pre><code>public class Main extends Application {
      Controller C = new Controller();
  
      @Override
      public void start(Stage stage) throws Exception {
          Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
          Scene scene = new Scene(root, 300, 275);
          stage.setTitle("FXML Welcome");
          stage.setScene(scene);
          stage.show();
          C.handleSubmitButtonAction();//Error happens here.
      }
  
      public static void main(String[] args) {
          launch(args);
      }
  }
  </code></pre>
  
  <p>Controller class:</p>
  
  <pre><code>public class Controller{
      @FXML public Text actiontarget;
  
      @FXML protected void handleSubmitButtonAction() {
          actiontarget.setText("Sign in button pressed");
      }
  }
  </code></pre>
  
  <p>FXML code:</p>
  
  <pre class="lang-xml prettyprint-override"><code>&lt;GridPane fx:id="GridPane" fx:controller="sample.Controller" xmlns:fx="http://javafx.com/fxml" alignment="center" hgap="10" vgap="10"&gt;
      &lt;children&gt;
          &lt;Text text="Welcome" GridPane.columnIndex="0" GridPane.rowIndex="0" GridPane.columnSpan="2"/&gt;
          &lt;Label text="User Name:" GridPane.columnIndex="0" GridPane.rowIndex="1"/&gt;
          &lt;TextField GridPane.columnIndex="1" GridPane.rowIndex="1"/&gt;
          &lt;Label text="Password:" GridPane.columnIndex="0" GridPane.rowIndex="2"/&gt;
          &lt;PasswordField fx:id="passwordField" GridPane.columnIndex="1" GridPane.rowIndex="2"/&gt;
          &lt;HBox spacing="10" alignment="bottom_right" GridPane.columnIndex="1" GridPane.rowIndex="4"&gt;
              &lt;Button text="Sign In" onAction="#handleSubmitButtonAction"/&gt;
          &lt;/HBox&gt;
          &lt;Text fx:id="actiontarget" GridPane.columnIndex="1" GridPane.rowIndex="6"/&gt;
      &lt;/children&gt;
  &lt;/GridPane&gt;
  </code></pre>