7

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

CDspace
  • 2,639
  • 18
  • 30
  • 36
Jason Bourne
  • 95
  • 1
  • 5

1 Answers1

12

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);
}
James_D
  • 201,275
  • 16
  • 291
  • 322