javafx IllegalArgumentException(已设置为另一个场景的根)

Jas*_*rne 2 javafx illegalargumentexception

我在更改应用程序中的场景时遇到问题,看起来像

Main screen > Login screen
Run Code Online (Sandbox Code Playgroud)

我将屏幕存储在as中,hashmap<String, Node>并且一切正常,直到我从登录屏幕返回到主屏幕并想再次加载登录屏幕,这是异常和代码:

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);
}
Run Code Online (Sandbox Code Playgroud)

当我创建新的锚定窗格时,它可以工作

Parent root = new AnchorPane(MyApplication.pages.get("LoginPage"));
Run Code Online (Sandbox Code Playgroud)

但我想了解如果我在同一阶段工作,为什么它给我一个例外

Jam*_*s_D 6

唯一的例外是不言而喻的:锚窗格不能是两个不同场景的根。不必每次都创建一个新场景,只需替换现有场景的根目录即可:

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