0

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

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
mk7
  • 150
  • 1
  • 9
  • 1
    Also, as an aside, rather than [`System.exit()`](https://docs.oracle.com/javase/8/docs/api/java/lang/System.html#exit-int-), ["the preferred way to explicitly terminate a JavaFX Application"](https://docs.oracle.com/javase/8/javafx/api/javafx/application/Application.html) is to use [`Platform.exit()`](https://docs.oracle.com/javase/8/javafx/api/javafx/application/Platform.html#exit--). – jewelsea Apr 18 '15 at 02:53
  • Thx jewelsea! you are right about Platform.exit(). Without that, the program didn't fully exit. – mk7 Apr 18 '15 at 04:09
  • Also, my codes above actually work! Earlier I didn't use the right instance of stage correctly. Now, I can see the confirm dialog popping up asking Yes or No. – mk7 Apr 18 '15 at 04:10

0 Answers0