Search code examples
javajavafxjavafx-8

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?


Solution

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