You may have noticed there is no Frame.close() or JFrame.close() method. How then do you close a JFrame? Closing a JFrame is difficult to get your head around mainly because there are so many variants on how you can do it. You can:
When the user clicks the close X, that does not make your JFrame object mysteriously disappear or force it to close, or go invisible. All it does is send your JFrame a WindowClosing event. Your JFrame is free to ignore the event, close the JFrame in any of the four usual ways, or do something else entirely.
The event in no way closes your JFrame or changes its state. It is totally up to you what happens. Receiving a WindowClosingEvent is not an eviction notice; it is just notification the user idly clicked an X. It does not mean the JFrame is closing or that it has to close, just that the user would like it to.
DO_NOTHING_ON_CLOSE is a bit of a misnomer. It should have been called USE_EVENT_HANDLER_ON_CLOSE. It means Swing does nothing to handle the events automatically, but hand the problem over to you at your windowClosing method.
If you put no code at all in your windowClosing method, the event would be ignored. The user could click the X, but nothing would happen. You are free to put any code your heart desires in there, whatever you want to happen when the user clicks X.
this.setDefaultCloseOperation ( JFrame.DISPOSE_ON_CLOSE );
this.setDefaultCloseOperation ( JFrame.HIDE_ON_CLOSE );Believe it or not, this is the default. Beware!
this.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );
this.setDefaultCloseOperation ( JFrame.DO_NOTHING_ON_CLOSE );
this.setDefaultCloseOperation ( JFrame.DISPOSE_ON_CLOSE );It will default to HIDE_ON_CLOSE which will leave JFrames lying about un-garbage collected.
Be careful not to cast adrift an undisposed JFrame with no references to it. It can never be garbage collected.
To iconify (minimise), maximize etc. programmatically see Frame.setExtendedState( Frame.ICONIFIED ); Other constants you can use include Frame.MAXIMIZED_HORIZ, Frame.MAXIMIZED_VERT, Frame.MAXIMIZED_BOTH, and Frame.NORMAL. Prior to Java 1.14 you had to use Frame.setState( Frame.ICONIFIED );
Oddly, for JInternalFrames, you have to use a different technique entirely using the DeskTopManager class.
![]() |
and suggestions to improve this page to Roedy Green : | ||
| Canadian Mind Products | |||
| mindprod.com IP:[65.110.21.43] | |||
| Your face IP:[38.103.63.18] | The information on this page is for non-military use only. | ||
| You are visitor number 56,041. | Military use includes use by defence contractors. | ||
| You can get a fresh copy of this page from: | or possibly from your local J: drive (Java virtual drive/Mindprod website mirror) | ||
| http://mindprod.com/jgloss/close.html | J:\mindprod\jgloss\close.html | ||