JFrame catch dispose event
I spent days searching for a solution to the same issue as the OP. It was hiding in plain sight.
The windowClosed()
method is event driven, meaning it is called whenever a frame is closed, in any way:
- by the X button
- By invoking
myFrame.dispose()
JFrame myFrame = new JFrame();
myFrame.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosed(java.awt.event.WindowEvent windowEvent) {
// your code
}
});
Source: https://alvinalexander.com/blog/post/jfc-swing/closing-your-java-swing-application-when-user-presses-close-but
on that frame i also have a close button (to make it more user friendly)
Check out the Closing an Application solution to handle this. All you really need to do is add the "ExitAction" to your button, but you can use the whole approach if you want.