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
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.
this is 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. And I want it to return the current text in the textField.
You must run load()
before you get the controller.
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
? Please, provide more example of your code. I don't know what's happening in your FXML
file. I think there may be some kind of xml code missing.
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
load()
before you get the controller.stop()
method in my mainApp and got back the saved value in it.Not sure this is the best way to do it but it worked for me, Thanks for all the help.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.