如何在 java fx 2 中更改 TextField 的文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10601648/
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 01:47:54  来源:igfitidea点击:

how to change the text of TextField in java fx 2

javanullpointerexceptiontextfieldjavafx-2

提问by Bipin Bhandari

I have a TextFieldin which there is some text but I want to change that text on some event but I am getting the NullPointerException.

我有一个TextField其中有一些文本但我想在某个事件中更改该文本但我得到了NullPointerException.

I am using setText()method but still its not working. I am calling that function from other class .

我正在使用setText()方法,但仍然无法正常工作。我正在从其他类调用该函数。

Any Help?

任何帮助?

Thanks in advance.

提前致谢。

回答by Mike Baran

At beginning of the controller's class definition:

在控制器类定义的开头:

@FXML private TextField txtDescription;

Within the initialize method, add:

在 initialize 方法中,添加:

txtDescription = new TextField();

Within a method that acts on that text field, something like:

在作用于该文本字段的方法中,例如:

txtDescription.setText("This is my new text.");

回答by gokcand

Make sure that you have a TextField definition in your .fxmlfile with the following:

确保您的.fxml文件中有一个 TextField 定义,其中包含以下内容:

 fx:id="myCoolTextField"

If you don't have that, init the text field in your display() method with the following:

如果没有,请使用以下内容在 display() 方法中初始化文本字段:

myCoolTextField = new TextField();

You may also override the special initialize()method. This method is being called every time your scene updated.

您还可以覆盖特殊的initialize()方法。每次更新场景时都会调用此方法。

@FXML
public void initialize() {
    myCoolTextField.setText("Here is my updated text.");
}