What's the correct way to get a JFrame
to close, the same as if the user had hit the X
close button, or pressed Alt+F4 (on Windows)?
I have my default close operation set the way I want, via:
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
It does exactly what I want with the aforementioned controls. This question isn't about that.
What I really want to do is cause the GUI to behave in the same way as a press of X
close button would cause it to behave.
Suppose I were to extend WindowAdaptor
and then add an instance of my adaptor as a listener via addWindowListener()
. I would like to see the same sequence of calls through windowDeactivated()
, windowClosing()
, and windowClosed()
as would occur with the X
close button. Not so much tearing up the window as telling it to tear itself up, so to speak.
Based on the answers already provided here, this is the way I implemented it:
The JFrame gets the event to close and upon closing, exits.
This answer was given by Alex and I would like to recommend it. It worked for me and another thing it's straightforward and so simple.
Posting what was in the question body as CW answer.
Wanted to share the results, mainly derived from following camickr's link. Basically I need to throw a
WindowEvent.WINDOW_CLOSING
at the application's event queue. Here's a synopsis of what the solution looks likeNot only closes the JFrame but the shutdowns the entire application, hence "EXIT ON CLOSE"
To achieve the same result you have to effectively exit the application, for that simply call
The effect is exactly the same.
Not too tricky.
This examples shows how to realize the confirmed window close operation.
The window has a Window adapter which switches the default close operation to
EXIT_ON_CLOSE
orDO_NOTHING_ON_CLOSE
dependent on your answer in theOptionDialog
.The method
closeWindow
of theConfirmedCloseWindow
fires a close window event and can be used anywhere i.e. as an action of an menu item