user5946312
user5946312

Reputation:

Display a confirmation dialogue when the user try to exit the application (Press X button)

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?

Upvotes: 1

Views: 1088

Answers (3)

NethakaDeSaram
NethakaDeSaram

Reputation: 11

I Followed this approach...

After creating my stage I use this code to launch a popup and exit...

stage.setOnCloseRequest((WindowEvent arg0) -> {
        arg0.consume();
        Alert exitAlert = new Alert(AlertType.CONFIRMATION);
        exitAlert.setTitle("Exit Confirmation");
        exitAlert.setHeaderText(null);
        exitAlert.setContentText("Do you really need to exit ?");

        ButtonType yesBtn = new ButtonType("Yes", ButtonData.YES);
        ButtonType noBtn = new ButtonType("No", ButtonData.NO);

        exitAlert.getButtonTypes().setAll(yesBtn, noBtn);
        exitAlert.initOwner(getScene().getWindow());
        exitAlert.showAndWait();
        if (exitAlert.getResult().getButtonData() == ButtonData.YES) {
            Platform.exit();
            System.exit(0);
        }
    });

Upvotes: 1

brian
brian

Reputation: 10989

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());
});

Upvotes: 2

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();
    });
});

Upvotes: 1

Related Questions