Disabling red 'X' button from closing entire JavaFX program w/ Java8?

4.6k views Asked by At

I'm running into a bit of a problem. I'm creating a program for a client. In the program, I have implement a dedicated 'close/shut down' button - which requires a password in order to properly shut down. But an alternative (and less safe) way of closing the program is by hitting the red close or 'X' button: top right (Windows) or top left(Mac).

I do not want the red x button to actually close the entire program. What I would like to know: is it possible to completely disable the red 'x' button from closing the entire program? If possible, could someone provide code for this?

What I'm using: IntelliJ IDEA (Ultimate), JavaFX with Java 8, Dev. Language: Java

1

There are 1 answers

5
fabian On BEST ANSWER

Add a event handler to the onCloseRequest event of the stage. This allows you to prevent the window from closing by consuming the event and executing your own shutdown procedure instead:

private void shutdown(Stage mainWindow) {
    // you could also use your logout window / whatever here instead
    Alert alert = new Alert(Alert.AlertType.NONE, "Really close the stage?", ButtonType.YES, ButtonType.NO);
    if (alert.showAndWait().orElse(ButtonType.NO) == ButtonType.YES) {
        // you may need to close other windows or replace this with Platform.exit();
        mainWindow.close();
    }
}

@Override
public void start(Stage primaryStage) {
    primaryStage.setOnCloseRequest(evt -> {
        // prevent window from closing
        evt.consume();

        // execute own shutdown procedure
        shutdown(primaryStage);
    });

    StackPane root = new StackPane();

    Scene scene = new Scene(root, 100, 100);

    primaryStage.setScene(scene);
    primaryStage.show();
}