1

I want to modify the default exit procedure in my javafx application to display a confirmation dialogue to the user. The confirmation dialogue will exit the application if the user chooses OK and will keep the application running when user chooses Cancel.

What should I do to make this in javaFX?

  • I tried overriding the stop() method in the main class but it still closes the application even before the confirmation Prompt is displayed –  Dec 20 '16 at 02:16
  • 1
    I found the best answer is in this thread: http://stackoverflow.com/questions/13727314/prevent-or-cancel-exit-javafx-2 – R. Salame Dec 20 '16 at 02:21

2 Answers2

2

You can use Alert since 8.40

stage.setOnCloseRequest(evt -> {
    Alert alert = new Alert(AlertType.CONFIRMATION);
    alert.setTitle("Confirm Close");
    alert.setHeaderText("Close program?");
    alert.showAndWait().filter(r -> r != ButtonType.OK).ifPresent(r->evt.consume());
});
brian
  • 10,619
  • 4
  • 21
  • 79
1
primaryStage.addEventFilter(WindowEvent.WINDOW_CLOSE_REQUEST, e->{
    e.consume();
    Popup popup = new Popup();
    HBox buttons = new HBox();
    Button close = new Button("close");
    Button cancel = new Button("cancel");
    buttons.getChildren().addAll(close,cancel);
    buttons.setPadding(new Insets(5,5,5,5));
    popup.getContent().add(buttons);
    popup.show(primaryStage);
    close.setOnAction(ex -> {
        Platform.exit();
    });
    cancel.setOnAction(ec -> {
        popup.hide();
    });
});