Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Closing a Swing App Through Menu ( File -> Exit )

843806Mar 30 2009 — edited Apr 1 2009
I've been pretty heavily working with Swing for the last year, and my current nemesis is that I still can't figure out how to properly exit the application through an action other than clicking the window X. For example, by clicking Exit from a File menu. I would like it to reliably fire a window closing event and then reliably terminate the program (there are other things that should probably happen, like a window closed event, but the window closing event is the only one I really care about because it is where I do my close down tasks like saving state). I can reliably terminate the program by calling System.exit(0), but I'm still having trouble getting a window closing event to fire reliably.

I've tried combinations of the following in my JFrame exit operation:

* setVisible(false)
* dispose()
* System.exit(0)

I keep thinking I have it solved only to discover through later testing that it still doesn't work under various situations.

If I don't include a System.exit(0), there are cases where the program will not terminate. If I include a System.exit(0), there are cases where the window closing event doesn't fire.

If I use System.exit(0), does it exit immediately even if there are still events in the event queue? That could explain why the window closing event is unreliable in my tests. If this is the case, is there a way to wait until the event queue is empty? Or should I not be using System.exit(0)? And if I shouldn't use System.exit(0), what could cause my program to not terminate after calling setVisible(false) and dispose()?

This seems like a beginner question, but I just can't seem to find any information on how to do this in my searches.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Apr 29 2009
Added on Mar 30 2009
17 comments
2,350 views