0

I created a JavaFX project. Here is what it looks like:

JavaFX project In SceneBuilder I created a BorderPane with one label with the id label. In my SampleController I use this Label named label:

Label label;
public SampleController() {
    label.setText("hi");
}

If I remove label.setText("hi"); the code works fine but when the code is there I get the following error. It is very long, here is a part of it.

javafx.fxml.LoadException:

I think that is the most important part. I can however add buttons and their actions and it still works fine. now i added.

@FXML
private Pane taskPane;
private void initialize() {
        System.out.println(taskPane.getWidth());
    }

i did the same thing as the label with a pane and i get a null pointer exception.

  • Hey there, I suggest you add the full stacktrace in there, because the most important thing is not just the exception name, but also where it occurs. In particular there should be a "Caused by"-block somewhere telling you what the problem is. Sadly I am not a JavaFX-expert and thus cannot help you, but I guess with a full stacktrace your odds of receiving a helpful answer are higher. – Igor Mar 24 '18 at 04:20
  • 1
    If buttons and there actions work fine, controller definition in the controller should be ok. Next, what you want to look at is the `fx:id` of the Label. If you can post the fxml in the question, it would help to resolve your query faster. – ItachiUchiha Mar 24 '18 at 07:32

1 Answers1

0

When the fxml is loaded the controller instance is created before FXMLLoader injects objects into the fields of the controller. Since you're trying to access the Label in the constructor invoked during the contollers creation this results in a NullPointerException.

Move the initialisation of the Label to the initialize method. This method is invoked by FXMLLoader just before returning from the load method, i.e. after injecting the fields:

@FXML
Label label;
public SampleController() {}

@FXML
private void initialize() {
    label.setText("hi");
}

Simply setting the text property of a label can be done from the fxml too of course...

fabian
  • 80,457
  • 12
  • 86
  • 114