java 如何在 onAction 方法中从 TextField 获取文本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14299607/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get text from TextField in onAction method?
提问by woyaru
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
我的一种Button
on action 方法中获取文本时,我收到 NullPointerException 。这是我的 textField 定义:
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:
这是我的按钮及其 on action 方法:
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?
我进入NullPointerExcpetion
这一行:String text = textField.getText();
。如何在 onAction 方法中从 textField 获取文本?
采纳答案by Reimeus
One possibility is that you are shadowing your TextField
in a method or constructor. This appears to be a possibility given that the local variable has not been declared as final
.
If your EventHandler
is using a class member variable called textField
, then replace
一种可能性是您TextField
在方法或构造函数中隐藏了您的方法。鉴于局部变量尚未声明为 ,这似乎是一种可能性final
。如果您EventHandler
使用的是名为 的类成员变量textField
,则替换
TextField textField = new TextField();
with
和
textField = new TextField();