Faahmed
Faahmed

Reputation: 425

Perform an action as soon as user closes (Xs out) JFrame

Basically it's a client program with a GUI so I want to close the sockets when the user closes the client program. Is there is Listener or something that will allow me to do this?

Upvotes: 0

Views: 189

Answers (3)

Marco
Marco

Reputation: 1460

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.addWindowListener(new WindowAdapter() {

    @Override
    public void windowClosing(WindowEvent e) {
        // do stuff
    }
});

Note that this will only be called when the default close operation has been set to EXIT_ON_CLOSE before the frame is closed via the (x) button. The default is HIDE_ON_CLOSE which technically does not close the window, therefore the listener would not be notified.

Upvotes: 2

syb0rg
syb0rg

Reputation: 8247

Add a WindowListener for the closing event:

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.addWindowListener(new WindowAdapter()
{
    public void windowClosing(WindowEvent e)
    {
        // Do stuff
    }
});

For more help, look at this tutorial on WindowListener's.

Upvotes: 2

millimoose
millimoose

Reputation: 39960

To refer to this from an enclosing scope, use this:

class MyFrame extends JFrame {

    public MyFrame() {
        this.addWindowListener(
            // omitting AIC boilerplate

            // Use the name of the enclosing class
            MyFrame.this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            // ...
        }
    }
}

Or store it in a variable with a different name:

class MyFrame extends JFrame {

    public MyFrame() {
        final JFrame thisFrame = this;
        this.addWindowListener(
            // omitting AIC boilerplate

            // Use the name of the enclosing class
            thisFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            // ...
        }
    }
}

Upvotes: 1

Related Questions