禁用红色“X”按钮关闭整个 JavaFX 程序 w/Java8?

Yur*_*yan 3 javafx button disabled-control

我遇到了一点问题。我正在为客户创建一个程序。在程序中,我实现了一个专用的“关闭/关闭”按钮——它需要一个密码才能正确关闭。但是另一种(不太安全)关闭程序的方法是点击红色关闭或“X”按钮:右上角(Windows)或左上角(Mac)。

我不希望红色 x 按钮实际关闭整个程序。我想知道的是:是否可以完全禁用红色“x”按钮关闭整个程序?如果可能,有人可以为此提供代码吗?

我在用什么:IntelliJ IDEA(终极版)、JavaFX 和 Java 8、Dev。语言:Java

fab*_*ian 8

onCloseRequest为舞台的事件添加一个事件处理程序。这允许您通过使用事件并执行您自己的关闭程序来防止窗口关闭:

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();
}
Run Code Online (Sandbox Code Playgroud)