JavaFX - getScene() returns null

柔情痞子 提交于 2019-11-29 13:29:27

you are trying to get the scene for an object that has not been initialized yet. if you were doing the same operation in

@Override 
    public void initialize(URL fxmlFileLocation, ResourceBundle resources) {
    Stage stage = (Stage) vboxRoot.getScene().getWindow();
}

or if you have an event that triggers once you click something (which executes after the scene has loaded)

@FXML
private void action(ActionEvent event) throws IOException {
    Stage stage = (Stage) vboxRoot.getScene().getWindow();
}

This would work!

I have run into this issue and have found by placing a call to a method like this (When the scene becomes visible and is attached to the node, this will fire):

 private void determinePrimaryStage() {
        rootPane.sceneProperty().addListener((observableScene, oldScene, newScene) -> {             
            if (oldScene == null && newScene != null) {
                // scene is set for the first time. Now its the time to listen stage changes.
                newScene.windowProperty().addListener((observableWindow, oldWindow, newWindow) -> {
                    if (oldWindow == null && newWindow != null) {
                        primaryStage = (Stage)newWindow;
                    }
                });
            }
        });
    }`

Then I can do something like this later:

if(primaryStage == null) {
    Platform.runLater(()-.{......
}else {
   //do whatever
}

Hope this helps.

Implementing the Initializable interface did not work for me(Java 8). The method getScene() always returned null for me. So i had to do the following:

FXMLLoader loader = new FXMLLoader(getClass().getResource("MyGui.fxml"));
Parent root = (Parent)loader.load();
//do stage and scene stuff - i skip it here
MyController controller = (MyController)loader.getController();
stage.setOnShown(controller::adjustUI);

And in the controller i have:

public void adjustUI(WindowEvent event) {
    Scene scene = myComponent.getScene();
    //do stuff and do ui adjustments here
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!