JavaFx:What if I want to do something after initialize(),before the scene show,how can I achieve this?

10.9k views Asked by At

I want to do something ,after the controller's initialize() method done,but before the scene show.Is there any method will be invoked before the scene show?I want to put some code into the method.

FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("sample.fxml"));
AnchorPane pane = loader.load();
Scene gameScene = new Scene(pane);
//I load a secne above,the I will get the controller,set some properties,then,use the properties to read a file before the secene show.
GameUIController controller = loader.getController();
controller.setGameFileLoacation("game1.txt");//I set a property here.I want to use it to read game file,and load game,set some necessary UI.
primaryStage.setScene(gameScene);//this tow statement will show the scene.
primaryStage.show();

I can't put code into initialize() method,because it will invoked when the fxml file loads(when I not yet to get the controller).So,how can I do?

Thanks verymuch !

1

There are 1 answers

1
Sarfaraz Khan On BEST ANSWER

One solution that I find

 primaryStage.addEventHandler(WindowEvent.WINDOW_SHOWING, new  EventHandler<WindowEvent>()
    {
        @Override
        public void handle(WindowEvent window)
        {
            //Your code 
        }
    });

This event occurs on window just before it is shown.doc link