How to programmatically close a JFrame

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.

17 Answers
17

Leave a Comment