JavaFX FileChooser Throws Error (probably easy fix, but still confused)
This is the third question I've seen in two days that's been caused by people re-initializing fields that have been @FXML
-injected by the FXMLLoader
.
The point of @FXML
is that you tell the FXMLLoader
to initialize that field with the object that was created by parsing the FXML file. When you then execute
btnBrowse = new Button();
in your initialize()
method, you create a new button and no longer have a reference to the one that was created for you when the FXML was parsed.
So, now it should be pretty obvious that btnBrowse.getScene()
will return null
(because the button was never added to a scene) and btnBrowse.getScene().getWindow()
will generate a NullPointerException
.
Just take those three lines out of your initialize()
method.
Can I ask where you saw to re-initialize those fields like that? If there's some popular resource out there that's spreading incorrect code, it needs to be taken down.