I'm looking to force-close a Java window even if a function is currently running - is there a way to do this? I have some functions that take quite a while in certain conditions (eg. running from a CD or another non-local location) and I want to be able to force-stop those functions and completely exit the program. Is this possible? And how can I go about doing it?
My code for exiting is below:
this.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent windowEvent) {
if (closeApplication()) {
System.exit(0);
}
}
});
And the closeApplication() function:
private boolean closeApplication() {
final JFrame temp = this;
int exitDialogResult = JOptionPane.showConfirmDialog(temp,
"Are you sure you want to exit?", "Really Closing?",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE);
if (exitDialogResult == JOptionPane.YES_OPTION) {
//code here to stop various processes
return true;
}
else {
return false;
}
}
Quick edit to clarify: when my program is executing a long-running function and I attempt to close the window, the window listener doesn't even register the click.
The problem you are facing is obvious: Your applications is getting "frozen" during long running background task because it executes on event dispatch thread. Use SwingWorker. That way, your GUI will remain responsive while your long running task runs on background thread. You could use System.exit()
for termination, but safest way would be to wait until your long running task is done.