title: JavaFX Dialog: Run onClosingRequest only when Ok button pressed
body: <p>I have a form Dialog and I want to add a confirmation alert before the dialog closes.</p>
  
  <p>The dialog is not to close until confirmed Ok.
  This I can prevent by consuming the event.</p>
  
  <p>It should only confirm on clicking the Dialog Ok, not on Cancel.
  Problem is, I cannot see which button was clicked on the event. So the Alert confirmation is shown for both OK and CANCEL buttons on the dialog.</p>
  
  <p>How can I prevent the onClosingReqeust for cancel button?</p>
  
  <pre><code>import javafx.application.Application;
  import javafx.application.Platform;
  import javafx.scene.Scene;
  import javafx.scene.control.Alert;
  import javafx.scene.control.Alert.AlertType;
  import javafx.scene.control.ButtonType;
  import javafx.scene.control.Dialog;
  import javafx.scene.control.Label;
  import javafx.scene.control.TextField;
  import javafx.scene.layout.GridPane;
  import javafx.scene.layout.StackPane;
  import javafx.stage.Modality;
  import javafx.stage.Stage;
  import javafx.stage.Window;
  
  public class DialogTestApplication extends Application {
  
      public static void main(String[] args) {
          launch(args);
      }
  
      class MyDialog extends Dialog&lt;ButtonType&gt; {
  
          public MyDialog(Window window) {
              setTitle("MyDialog");
              initModality(Modality.WINDOW_MODAL);
              initOwner(window);
              setResizable(true);
  
              GridPane contentPane = new GridPane();
              contentPane.add(new TextField(), 0, 0);
              getDialogPane().setContent(contentPane);
  
              getDialogPane().getButtonTypes().addAll(ButtonType.OK, ButtonType.CANCEL);
  
              setOnCloseRequest(event -&gt; {
                  Alert alert = new Alert(AlertType.CONFIRMATION);
                  alert.showAndWait().ifPresent(response -&gt; {
                      if (response == ButtonType.CANCEL) {
                          event.consume();
                      }
                  });
              });
          }
      }
  
      @Override
      public void start(Stage primaryStage) throws Exception {
          final StackPane root = new StackPane();
          final Label rootLabel = new Label("DialogTestApplication");
          root.getChildren().add(rootLabel);
          final Scene scene = new Scene(root, 400, 150);
          primaryStage.setScene(scene);
          primaryStage.setTitle("DialogTestApplication");
          primaryStage.show();
  
          Platform.setImplicitExit(true);
          MyDialog dialog = new MyDialog(primaryStage);
          dialog.showAndWait().ifPresent(response -&gt; {
              if (response == ButtonType.OK) {
                  System.out.println("OK");
              }
              Platform.exit();
          });
      }
  }
  </code></pre>