JavaFx:What if I want to do something after initia

2019-02-20 16:57发布

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条回答
来,给爷笑一个
2楼-- · 2019-02-20 17:15

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

查看更多
登录 后发表回答