问题
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