title: JavaFX - Label -- How to Access Class Member
body: <p>So my question is very simple.  I can access class members <em>in a separate class</em> when they are a <code>String</code> rather than a <code>Label</code>, but I can't seem to, when they <em>are</em> <code>Label</code>.  Using JDK 7u6 (w/ JavaFX 2.2).</p>
  
  <p>Simple examples.  First one works, second one doesn't.  <code>foo.label</code> can be assigned in the first example, but I get a NullPointer on the second example.  Can anyone explain why <code>foo.label</code> is null in the second example below?</p>
  
  <p>UPDATE: I removed the @FXML annotations from my original question, because I didn't think they were necessary to the problem I was having.  Also, see my comment on the <a href="https://stackoverflow.com/a/12468971/492404">answer by @jewelsea</a> ... Finally, I have added my FXML file, for completeness (at bottom of Q).</p>
  
  <p>This works:</p>
  
  <pre><code>// Example 1:
  public class SampleController implements Initializable {
      Foo foo = new Foo();
  
      public void handleButtonAction(ActionEvent event) {
          System.out.println("You clicked me!");
          foo.label = "Hello World!";
          System.out.println(foo.label);
      }
  
      @Override public void initialize(URL url, ResourceBundle rb) {
      }    
  }
  
  // Example 1 -- Foo.java:
  public class Foo {
      public String label;
  }
  </code></pre>
  
  <p>And this <em>does not</em> work:</p>
  
  <pre><code>// Example 2:
  public class SampleController implements Initializable {
      Foo foo = new Foo();
  
      public void handleButtonAction(ActionEvent event) {
          System.out.println("You clicked me!");
          foo.label.setText("Hello World!");  // gives NullPointer exception !!
      }
  
      @Override public void initialize(URL url, ResourceBundle rb) {
      }    
  }
  
  // Example 2 -- Foo.java:
  import javafx.scene.control.Label;
  
  public class Foo {
      public Label label;
  }
  </code></pre>
  
  <p>Here is my FXML file, for either of the examples above:</p>
  
  <pre><code>&lt;AnchorPane id="AnchorPane" prefHeight="200" prefWidth="320" xmlns:fx="http://javafx.com/fxml" fx:controller="javafxapplication4.SampleController"&gt;
      &lt;children&gt;
          &lt;Button layoutX="126" layoutY="90" text="Click Me!" onAction="#handleButtonAction" fx:id="button" /&gt;
          &lt;Label layoutX="126" layoutY="120" minHeight="16" minWidth="69" fx:id="label" text="hey!" /&gt;
      &lt;/children&gt;
  &lt;/AnchorPane&gt;
  </code></pre>