JavaFX: How to get stage from controller during initialization?

I want to handle stage events (i.e. hiding) from my controller class. So all I have to do is to add a listener via

((Stage)myPane.getScene().getWindow()).setOn*whatIwant*(...);

but the problem is that initialization starts right after

Parent root = FXMLLoader.load(getClass().getResource("MyGui.fxml"));

and before

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 !goddamn! 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?


Solution 1:

You can get the instance of the controller from the FXMLLoader after initialization via getController(), but you need to instantiate an FXMLLoader instead of using the static methods then.

I'd pass the stage after calling load() directly to the controller afterwards:

FXMLLoader loader = new FXMLLoader(getClass().getResource("MyGui.fxml"));
Parent root = (Parent)loader.load();
MyController controller = (MyController)loader.getController();
controller.setStageAndSetupListeners(stage); // or what you want to do

Solution 2:

All you need is to give the AnchorPane an ID, and then you can get the Stage from that.

@FXML private AnchorPane ap;
Stage stage = (Stage) ap.getScene().getWindow();

From here, you can add in the Listener that you need.

Edit: As stated by EarthMind below, it doesn't have to be the AnchorPane element; it can be any element that you've defined.