[英]java.lang.NullPointerException when trying to get the text of a textfield in mainApp when app is closing
I am new to javaFX and i am trying to get the value of a text field when my application is closing so i used我是 javaFX 的新手,我试图在我的应用程序关闭时获取文本字段的值,所以我使用了
FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/Scene.fxml"));
FXMLController controllerClass = loader.getController();
loader.load();
controllerClass.getTextFieldValue();
System.out.println("closing");
inside里面
stage.setOnCloseRequest()
but i always get a java.lang.NullPointerException.但我总是得到一个 java.lang.NullPointerException。
this is getTextfieldValue()这是 getTextfieldValue()
System.out.println(textField.getText());
so basically this is what I want to achieve, I want to get the value in a text field when the my application is closing.所以基本上这就是我想要实现的,我想在我的应用程序关闭时获取文本字段中的值。 so I have my
stage.onCloseRequest()
method in my mainApp class but the textField.getText() is always returning an empty string.所以我的 mainApp 类中有我的
stage.onCloseRequest()
方法,但 textField.getText() 总是返回一个空字符串。 And I want it to return the current text in the textField.我希望它返回 textField 中的当前文本。
You must run load()
before you get the controller.您必须在获得控制器之前运行
load()
。
Try this code:试试这个代码:
FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/Scene.fxml"));
loader.load();
FXMLController controllerClass = loader.getController();
controllerClass.getTextFieldValue();
System.out.println("closing");
Did you forget to add fx:id
in your Scene.fxml
?您是否忘记在
Scene.fxml
添加fx:id
? Please, provide more example of your code.请提供更多代码示例。 I don't know what's happening in your
FXML
file.我不知道您的
FXML
文件中发生了什么。 I think there may be some kind of xml code missing.我认为可能缺少某种 xml 代码。
Although I don't know what you are trying to achieve, but I think there is easier and correct way to do it.虽然我不知道你想要实现什么,但我认为有更简单和正确的方法来做到这一点。
FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/Scene.fxml")));
loader.setController(new FXMLController()); // you can not get controller, unless you set it first
FXMLController controllerClass = loader.getController();
controllerClass.getTextFieldValue();
This always be null
if you do not set value to getTextFieldValue
before如果您之前未将值设置为
getTextFieldValue
,则这始终为null
load()
before you get the controller.load()
然后再获取控制器。stop()
method in my mainApp and got back the saved value in it.stop()
方法并取回了其中保存的值. Not sure this is the best way to do it but it worked for me, Thanks for all the help.不确定这是最好的方法,但它对我有用,谢谢大家的帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.