In my GUI for my program, I have a line:
window.setOnCloseRequest(closeProgram());
This is run whenever the user presses the X
button on the Window frame (not a button I made, but is default on every single GUI application).
showWarningWindow
is a boolean method which shows a confirmation window about closing the program. If true, it will run Platform.exit();
I am 100% sure that my showWarningWindow()
method returns false
, and yet the application still closes. Why is this and how can I stop it from happening?
/**
* 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();
}
}
}
As in the documentation,
The installed event handler can prevent window closing by consuming the received event.
So you need
window.setOnCloseRequest(event -> closeProgram(event));
and
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();
}
}
}
Without this, your window will close no matter the return value of showWarningWindow
. If it happens to be the last window open, and Platform.isImplicitExit()
returns true (the default), then the application will exit.