I'm trying to set a TextField
's value when the respective FXML file is loaded, but when I tried to set a default value on the TextField
in the method where the FXML is loaded, in this case in the writeBtnClick()
method, it throws a NullPointerException
.
To my understanding, an element is not initialized until the FXML is loaded, so for whatever reason after loading the FXML file, the element is still not recognized.
Controller.java
public class Controller implements Initializable {
@FXML private TextField textField;
public void initialize(URL arg0, ResourceBundle arg1) {
}
public void writeBtnClick(ActionEvent event) throws IOException {
Stage stage = (Stage) ((Node)event.getSource()).getScene().getWindow();
stage.setScene(new Scene((Parent) FXMLLoader.load(getClass().getResource("WriteScene.fxml"))));
// the textfield I'm trying to set default value on
// this throws a NullPointerException
textField.setText("name");
}
To circumvent this problem I put the setText()
in initialize()
but of course that would also result in NullPointerException
if the controller class gets called before loading the correct fxml file.
This is the best way I could come up with but obviously it's very dirty and I feel like there should be a way to set the value on the writeBtnClick()
method where the scene actually gets loaded.
public void initialize(URL arg0, ResourceBundle arg1) {
// very hacky solution
if (textField != null) {
textField.setText("name");
}
}