pieAre5quare
pieAre5quare

Reputation: 65

JavaFX Scene builder controller

I am trying to manipulate the text in a TextField generated by Scene Builder. My controller looks like this:

@FXML
private TextField textDescr;

public void initialize(URL fxmlFileLocation, ResourceBundle resources) {
    textDescr = new TextField();
    assert textDescr != null : "fx:id=\"textDescr\" was not injected: check your FXML   file 'provingGroundsUI.fxml'.";
    Game.mainFSM.enter();
}
public void setText(String s) {
    // TODO Auto-generated method stub
    textDescr.setText(s);
}

I am getting a NullPointerException. I have tried bot with and without the textDescr = new TextField(); part. I don't quite understand....I thought that JavaFX initialized all the UI variables at the start of the program.

Upvotes: 0

Views: 2399

Answers (2)

Albrecht
Albrecht

Reputation: 28

  1. How looks your FXML?
  2. To manipulate the textDescr in the setText Function has a lot of risks. It is better to use a binded StringProperty:


    @FXML
    private Text textDescr;

    private StringProperty textProperty = new SimpleStringProperty();  

    @FXML
    void initialize() {
            assert textDescr != null : "fx:id=\"textDescr\" was not injected: check your FXML file 'TestView.fxml'.";
           textDescr.textProperty().bind(textProperty);
    }

    public ReadOnlyStringProperty textProperty(){
          return textProperty;
    }

Upvotes: 1

Arnold Galovics
Arnold Galovics

Reputation: 3416

Your controller class should implement Initializable

The @FXML annotation shows that the field will be initialized by the JavaFX. So make sure, you remove the new TextField thing.

Are you sure you assigned this controller in the FXML?

Upvotes: 1

Related Questions