I am getting NullPointerException when I am trying to get text from TextField in one of my Button on action method. This is my textField definition:
TextField textField = new TextField();
textField.setPromptText("Some text");
GridPane.setMargin(textField, new Insets(50, 50, 10, 50));
gridPane.add(textField, 0, 0);
And this is my button with its on action method:
Button button = new Button("Button");
GridPane.setMargin(button , new Insets(0, 50, 0, 50));
gridPane.add(button , 0, 1);
button.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
String text = textField.getText();
}
});
I am getting NullPointerExcpetion in this line: String text = textField.getText();. How can I get text from textField in onAction method?
One possibility is that you are shadowing your
TextFieldin a method or constructor. This appears to be a possibility given that the local variable has not been declared asfinal.If your
EventHandleris using a class member variable calledtextField, then replacewith