How do I use Alert dialog to ask a user to confirm if he/she wants to close a stage?
If the answer is Yes, process to use System.exit(0).
If answering No, exit the setOnCLoseRequest() method.
Platform.setImplicitExit(false);
stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
public void handle(WindowEvent e) {
boolean isExit = exitDialog();
if (!isExit) {
e.consume();
}
}
});
Also, I have
public boolean exitDialog() {
Alert alert = new Alert(AlertType.CONFIRMATION);
alert.setTitle("Mars Simulation Project");
alert.setHeaderText("Confirmation Dialog");
alert.initOwner(stage);
alert.setContentText("Do you really want to quit MSP?");
ButtonType buttonTypeYes = new ButtonType("Yes");
ButtonType buttonTypeNo = new ButtonType("No");
alert.getButtonTypes().setAll(buttonTypeYes, buttonTypeNo);
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == buttonTypeYes){
if (multiplayerMode != null)
if (multiplayerMode.getChoiceDialog() != null)
multiplayerMode.getChoiceDialog().close();
return true;
} else {
return false;
}
}
Note: I've tried using the advice from the link below by adding Platform.setImplicitExit() and e.consume() but they don't work!
EDIT: I'm wondering why the alert dialog doesn't even pop up at all. So WindowEvent e is not even captured. If that's the main culprit, how do I fix it?
Reference: Prevent/Cancel closing of primary stage in JavaFX 2.2