I am trying to build a simple appliaction using JavaFX. The problem is when i open a window (modal) the first time it is going well. The second time it's giving me this exception:
java.lang.IllegalArgumentException: AnchorPane[id=klantroot, styleClass=root]is already set as root of another scene
Since i am quite new to this I really don't have an idea on how to fix this. Can someone provide some help please. Thanks a lot in advance.
In my maincontroller I have this code:
private void showModal(Parent view, String title) {
Stage stage = new Stage();
Scene scene = new Scene(view);
stage.setScene(scene);
stage.initModality(Modality.WINDOW_MODAL);
stage.initOwner(this.root.getScene().getWindow());
stage.setTitle(title);
stage.showAndWait();
}
@FXML
private void handleToevoegenKlant() {
klantPresenter.setKlant(-1);
showModal(klantPresenter.getView(), "Toevoegen klant");
}
In my klantPresenter i have:
@FXML private Parent klantroot;
.....
public Parent getView() {
return klantroot;
}
@FXML
private void close() {
Stage stage = (Stage)getView().getScene().getWindow();
stage.close();
}
The code for KlantView.fxml starts with:
<AnchorPane
fx:id="klantroot"
fx:controller="presenter.KlantPresenter"
prefHeight="274.0" prefWidth="483.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1">
Every Scene
can have only one root element and every Parent
node can only be set as root for a just one scene. To set the parent as root to another scene you need to break previous relation.
The code Scene scene = new Scene(view);
in showModal(...)
method will assign the view as a root to the scene. So when the showModal(...)
is called again with the same instance of parent view, the error will arise.
The solution can vary depending on your app logic:
1) Create new instance of Parent view and send it as an argument.
2) Add lines into showModal(...)
if(view.getScene() != null)
view.getScene().setRoot(null);
to break old relation.
3) Your own solution?