I want to handle stage events (i.e. hiding) from my controller class. So all I have to do is to add a listener like this:
((Stage) myPane.getScene().getWindow()).setOn*whatIwant*(...);
But the problem is that initialization starts right after this code:
Parent root = FXMLLoader.load(getClass().getResource("MyGui.fxml"));
And before this code:
Scene scene = new Scene(root);
stage.setScene(scene);
Thus getScene returns null.
The only workaround I found by myself is to add a listener to myPane.sceneProperty, and when it becomes not null I get scene, add to it’s windowProperty my listener handling which I finally retrieve stage. And it all ends with setting desired listeners to stage events.
I think there are too many listeners.
Is it the only way to solve my problem?
You can get the instance of the controller from the
FXMLLoaderafter initialization viagetController(), but you need to instantiate anFXMLLoaderinstead of using the static methods then.I’d pass the stage after calling
load()directly to the controller afterwards: