Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 457
Chechulin Avatar asked Nov 06 '12 07:11

Chechulin


People also ask

How do you get stage on controller?

There are three main ways to get access a Stage from within a controller: Access the Stage through a node. Set the Stage using a custom controller method. Get the Stage through an ActionEvent.

What method is invoked to display a stage in JavaFX?

Showing a Stage The difference between the JavaFX Stage methods show() and showAndWait() is, that show() makes the Stage visible and the exits the show() method immediately, whereas the showAndWait() shows the Stage object and then blocks (stays inside the showAndWait() method) until the Stage is closed.

What does initialize method do in JavaFX?

[...] the controller can define an initialize() method, which will be called once on an implementing controller when the contents of its associated document have been completely loaded [...] This allows the implementing class to perform any necessary post-processing on the content.

What does JavaFX stage stage do?

A Stage in JavaFX is a top-level container that hosts a Scene, which consists of visual elements. The Stage class in the javafx. stage package represents a stage in a JavaFX application. The primary stage is created by the platform and passed to the start(Stage s) method of the Application class.


1 Answers

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 
like image 111
zhujik Avatar answered Oct 26 '22 20:10

zhujik