JavaFx:如果我想在initialize()之后做一些事情,在场景展示之前,我该如何实现呢?

时间:2015-06-19 03:10:36

标签: java javafx javafx-2 javafx-8

我想在控制器的initialize()方法完成之后,但在场景show之前做一些事情。在场景显示之前是否会调用任何方法?我想在方法中加入一些代码。

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();

我无法将代码放入initialize()方法,因为它会在fxml文件加载时调用(当我还没有得到控制器时)。那么,我该怎么办?

非常感谢!

1 个答案:

答案 0 :(得分:7)

我找到的一个解决方案

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

此事件在显示之前发生在窗口上。doc link