2

When I have a controller that accesses the controls of the FXML through @FXML, then I don't neeed to initialize them. I can just access them (result.setText("test") for example), as I can see in various examples. For some reason, that doesn't work for me and I can't find the reason. Can someone tell me the reason please?

public class WiderstandController implements Initializable {

    @FXML
    private TextField input;

    @FXML
    private Label result;

    @FXML
    private Button btn;

    @FXML
    private void berechne() {
        result.setText("test");
        System.out.println(result.getText());
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
    }

}

And here is the relevant FXML part (inside a Pane):

fx:controller="widerstand.WiderstandController"

Can you see what is wrong or do you need more? I don't want to spam everything here if we can find it already in that class.

EDIT: by not being able to access I mean that I get NullPointerException.

fabian
  • 80,457
  • 12
  • 86
  • 114
yemerra
  • 1,352
  • 4
  • 19
  • 44
  • 2
    Did you set `fx:id` attributes in your FXML? – Itai Feb 07 '16 at 00:48
  • Well, obviously you're getting a `NullPointerException` in method `berechne()` because `result` is null. The FXML Loader has not found a control to inject into your `result` variable. Can you show us the stack trace for your error, as well as the FXML for your controls? You've not given us enough information to say where the problem is. – scottb Feb 07 '16 at 00:49
  • @sillyfly This was the problem. That was hard to figure out tbh. Thanks. – yemerra Feb 07 '16 at 00:51
  • @sillyfly why don't you add it as an answer? – Sнаđошƒаӽ Feb 07 '16 at 00:59

1 Answers1

2

The mistake I made was not changing id to fx:id in the FXML file.

yemerra
  • 1,352
  • 4
  • 19
  • 44