So my question is very simple. I can access class members in a separate class when they are a String
rather than a Label
, but I can't seem to, when they are Label
. Using JDK 7u6 (w/ JavaFX 2.2).
Simple examples. First one works, second one doesn't. foo.label
can be assigned in the first example, but I get a NullPointer on the second example. Can anyone explain why foo.label
is null in the second example below?
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 answer by @jewelsea ... Finally, I have added my FXML file, for completeness (at bottom of Q).
This works:
// 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;
}
And this does not work:
// 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;
}
Here is my FXML file, for either of the examples above:
<AnchorPane id="AnchorPane" prefHeight="200" prefWidth="320" xmlns:fx="http://javafx.com/fxml" fx:controller="javafxapplication4.SampleController">
<children>
<Button layoutX="126" layoutY="90" text="Click Me!" onAction="#handleButtonAction" fx:id="button" />
<Label layoutX="126" layoutY="120" minHeight="16" minWidth="69" fx:id="label" text="hey!" />
</children>
</AnchorPane>