Issue
I am creative a java app where the user can click on the menu and select 'exit'. When they click 'exit' a pop-up dialogue box appears asking 'are you sure you want to exit?' the option for yes or no is there and these buttons work fine.
When this dialogue box is visible you can still click on the window behind and this will make that window active and place it above the pop up. I don't want that to happen, I only want the pop up window active and for it to stay on top until the user has clicked yes or no. This is the same for the red X in the top left of the window - I don't want the user to be able to click this if the pop up is displaying. Any ideas? I've had a go at consuming the event by using
event.consume();
I placed this within an if statement for when the stage2 (my pop up box) was showing and if a oncloserequest is called for stage1 (main window) then the event is consumed. This works fine but once the pop up box is closed (by selecting no) the event is still consumed.
Also when the pop up dialogue is showing you can still click on stage1 behind it and the popup box will be sent to the back.
Someone mentioned modal dialogue boxes? What is this? I don't understand
Solution
There's a property called stage.initOwner(Stage stg) that allows this to happen.
Example:
public class JavaFXApplication4 extends Application {
@Override
public void start(Stage stage) {
Button jb = new Button("Click");
jb.setOnMouseClicked(new EventHandler() {
@Override
public void handle(Event event) {
makeAnotherStage(stage);
}
});
GridPane gp = new GridPane();
gp.getChildren().add(jb);
Scene s = new Scene(gp);
stage.setScene(s);
stage.show();
}
private void makeAnotherStage(Stage st){
Stage s = new Stage();
GridPane gp = new GridPane();
Label l = new Label("Second Stage");
gp.getChildren().add(l);
Scene sc = new Scene(gp);
s.initOwner(st); <------- initOwner
s.initModality(Modality.WINDOW_MODAL); <------- Modality property
s.setScene(sc);
s.requestFocus();
s.show();
}
}
Oracle Documentation on Modality: https://docs.oracle.com/javafx/2/api/javafx/stage/Modality.html
Source: How to make the opened window must close at first before back to the main?
Answered By - Steven