Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 977
Jason Bourne Avatar asked Sep 20 '17 17:09

Jason Bourne


1 Answers

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);
}
like image 50
James_D Avatar answered Nov 08 '22 02:11

James_D