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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 15:47:44  来源:igfitidea点击:

How to get text from TextField in onAction method?

javajavafx-2

提问by woyaru

I am getting NullPointerException when I am trying to get text from TextFieldin one of my Buttonon action method. This is my textField definition:

当我尝试从TextField我的一种Buttonon 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 NullPointerExcpetionin 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 TextFieldin a method or constructor. This appears to be a possibility given that the local variable has not been declared as final. If your EventHandleris using a class member variable called textField, then replace

一种可能性是您TextField在方法或构造函数中隐藏了您的方法。鉴于局部变量尚未声明为 ,这似乎是一种可能性final。如果您EventHandler使用的是名为 的类成员变量textField,则替换

TextField textField = new TextField();

with

textField = new TextField();