javafx IllegalArgumentException (is already set as root of another scene)

♀尐吖头ヾ 提交于 2020-05-23 12:51:09

问题


I have problem with changing scenes in my application which looks like

Main screen > Login screen

I am storing screens in main file as hashmap<String, Node> and everything is good until I go back from login screen to main screen and want to load the login screen again, here is exception and code:

java.lang.IllegalArgumentException: AnchorPane@30561c33[styleClass=root]is already set as root of another scene

public static final HashMap<String, Parent> pages = new HashMap<>();

@FXML
private void LogIn(ActionEvent event) {
    Button button = (Button) event.getSource();
    Stage stage = (Stage) button.getScene().getWindow();
    if(stage.getScene() != null) {stage.setScene(null);}
    Parent root = MyApplication.pages.get("LoginPage");
    Scene scene = new Scene(root, button.getScene().getWidth(), button.getScene().getHeight());
    stage.setScene(scene);
}

It works when I'm creating new anchorpane

Parent root = new AnchorPane(MyApplication.pages.get("LoginPage"));

But I want to understand why it gives me an exception if I'm working on the same stage


回答1:


The exception is pretty self-explanatory: the anchor pane cannot be the root of two different scenes. Instead of creating a new scene every time, just replace the root of the existing scene:

@FXML
private void LogIn(ActionEvent event) {
    Button button = (Button) event.getSource();
    Scene scene = button.getScene();
    Parent root = MyApplication.pages.get("LoginPage");
    scene.setRoot(root);
}


来源:https://stackoverflow.com/questions/46328192/javafx-illegalargumentexception-is-already-set-as-root-of-another-scene

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!