0 0 0 0


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:


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.

Best Answer:

Best way to close a Swing frame programmatically is to make it behave like it would when the "X" button is pressed. To do that you will need to implement WindowAdapter that suits your needs and set frame's default close operation to do nothing (DO_NOTHING_ON_CLOSE).

Initialize your frame like this:

private WindowAdapter windowAdapter = null;
private void initFrame() {
    this.windowAdapter = new WindowAdapter() {
        // WINDOW_CLOSING event handler
        public void windowClosing(WindowEvent e) {
            // You can still stop closing if you want to
            int res = JOptionPane.showConfirmDialog(ClosableFrame.this, "Are you sure you want to close?", "Close?", JOptionPane.YES_NO_OPTION);
            if ( res == 0 ) {
                // dispose method issues the WINDOW_CLOSED event
        // WINDOW_CLOSED event handler
        public void windowClosed(WindowEvent e) {
            // Close application if you want to with System.exit(0)
            // but don't forget to dispose of all resources 
            // like child frames, threads, ...
            // System.exit(0);
    // when you press "X" the WINDOW_CLOSING event is called but that is it
    // nothing else happens
    // don't forget this

You can close the frame programmatically by sending it the WINDOW_CLOSING event, like this:

WindowEvent closingEvent = new WindowEvent(targetFrame, WindowEvent.WINDOW_CLOSING);

This will close the frame like the "X" button was pressed.

Copyright © 2011 Dowemo All rights reserved.    Creative Commons   AboutUs