Jemerson Damásio
Jemerson Damásio

Reputation: 47

JavaFX confusing event handling on System Exit

The code bellow generates an Alert Dialog with two buttons, Ok and Cancel; and it also works as expected: if I click Ok, the system exits, otherwise the dialogs vanishes.

The strange thing is: if I ommit the else block handling the event, the platform will always exit, not considering the button I clicked.

Is that really the expected behaviour? Am I missing something?

private void setCloseBehavior() 
{
    stage.setOnCloseRequest((WindowEvent we) -> 
    {
        Alert a = new Alert(Alert.AlertType.CONFIRMATION);
        a.setTitle("Confirmation");
        a.setHeaderText("Do you really want to leave?");                      
        a.showAndWait().ifPresent(response -> {
            if (response == ButtonType.OK) {
                Platform.exit();
            } else {
                we.consume();
            }
        });
    });
}

Upvotes: 0

Views: 598

Answers (1)

jewelsea
jewelsea

Reputation: 159291

Here is the documentation for windows.onCloseRequest:

Called when there is an external request to close this Window. The installed event handler can prevent window closing by consuming the received event.

So, if you don't consume the close request event in the close request handler, the default behavior will occur (the window will be closed).

You don't really need to invoke Platform.exit() in the close request handler because the default behavior is to exit, so you could simplify your logic. You only need to consume the close request event if the user does not confirm that they want to close:

stage.setOnCloseRequest((WindowEvent we) -> 
{
    Alert a = new Alert(Alert.AlertType.CONFIRMATION);
    a.setTitle("Confirmation");
    a.setHeaderText("Do you really want to leave?");   
    Optional<ButtonType> closeResponse = alert.showAndWait();
    if (!ButtonType.OK.equals(closeResponse.get())) {
        we.consume();
    }                   
});

There is a similar fully executable sample in the answer to the related StackOverflow question:

Upvotes: 1

Related Questions