在我的程序的 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/