Issue
So I have a Program that is based on Hydra. A Window pops up, when trying to close it, it closes but two more windows pop up in its place. There are two ways to close the window either by pressing the close button or the red cross.
My problem is the program is behaving very unpredictable sometimes it will close it and open 2 new ones sometimes it will not close and not open a new one.
WARNING!!!! if you execute this code you will have to kill the program via Task Manager or IDE.
@Override
public void start(Stage stage) throws Exception {
this.stage = stage;
this.stage.setTitle("Hail Hydra");
placeNewHeadRandomly();
this.stage.setScene(growHead());
this.stage.setOnCloseRequest(e -> {
cutOffHead();
});
this.stage.show();
}
private void placeNewHeadRandomly() {
// not important for this question but randomly changes windows X and Y.
}
private Scene growHead() {
// not important for this question creates a window with a button that calls cutOffHead();
VBox vbox = new VBox();
vbox.setPrefWidth(WINDOW_WIDTH);
vbox.setPrefHeight(WINDOW_HEIGHT);
vbox.setAlignment(Pos.CENTER);
vbox.setSpacing(10);
Label warning = new Label("Cut off one hydra head, two more will grow back in its place.");
Button sword = new Button("close");
sword.setOnAction(e -> cutOffHead());
vbox.getChildren().addAll(warning, sword);
return new Scene(vbox);
}
private void cutOffHead() {
this.stage.close();
try {
start(new Stage());
start(new Stage());
} catch (Exception e) {
e.printStackTrace();
}
}
Solution
You call start(new Stage())
in a row, but it's the same method of the same object. In the beginning of start
you save the parameter into this.stage
field. So, the first call saves into this field the result of the first new Stage()
and then later you overwrite it wth the result of the second new Stage()
. Now you have 2 new stages open, but this.stage
is referencing only the second one.
Answered By - Alex