JavaFX - onCloseRequest() 否决了我的 boolean 语句

标签 java javafx window

在我的程序的 GUI 中,我有一行:

window.setOnCloseRequest(closeProgram());

只要用户按下窗口框架上的 X 按钮(不是我制作的按钮,而是每个 GUI 应用程序上的默认按钮),就会运行此函数。

showWarningWindow 是一个 boolean 方法,它显示有关关闭程序的确认窗口。如果为 true,它将运行 Platform.exit();

我 100% 确定我的 showWarningWindow() 方法返回 false,但应用程序仍然关闭。这是为什么?我怎样才能阻止它发生?

/**
 * This method is called when the user wishes to close the program.
 */
private void closeProgram()
{
    if (logic.unsavedChangesExist())
    {
        if (showWarningWindow("You currently have unsaved changes made to the database."
                + "\nAre you sure you would like to exit without saving?"))
        {
            Platform.exit();
        }
    }
}

最佳答案

documentation中所示,

The installed event handler can prevent window closing by consuming the received event.

所以你需要

window.setOnCloseRequest(event -> closeProgram(event));

private void closeProgram(WindowEvent event)
{
    if (logic.unsavedChangesExist())
    {
        if (showWarningWindow("You currently have unsaved changes made to the database."
                + "\nAre you sure you would like to exit without saving?"))
        {
            Platform.exit();
        } else {
            event.consume();
        }
    }
}

如果没有这个,无论 showWarningWindow 的返回值如何,您的窗口都将关闭。如果它恰好是最后一个打开的窗口,并且 Platform.isImplicitExit() 返回 true(默认值),则 the application will exit .

关于JavaFX - onCloseRequest() 否决了我的 boolean 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34595719/

相关文章:

java.lang.NoClassDefFoundError

java - 如何使用注释在当前函数之前运行函数?

java - 任务只运行一次

python - Maya PySide 窗口 - 记住位置和大小

java - 将自定义 SSL 证书添加到信任库但保留 Java 8+ 中的默认 cacerts?

java - 某些文件的 maven-assembly-plugin

JavaFX - 中心文件选择器弹出窗口

JavaFX TabPane 选项卡不更新位置

c# - 获取焦点窗口名称

jQuery:在子窗口上接收文档准备就绪()