I'm building an instant messenger application.I need to add an action event on the default closing button of the Swing JFrame(The little "x").
When the client presses the X button,I need to tell the server that he goes offline and only after that action occures I have to close the window.I can't seem to find how to get an action listener on the default button.

- 15,743
- 6
- 59
- 89

- 687
- 2
- 8
- 21
-
3This type of question has only been asked over a hundred times here including: [JFrame On Close Operation](http://stackoverflow.com/questions/10468149/jframe-on-close-operation). Voting to close as a duplicate. – Hovercraft Full Of Eels Sep 26 '12 at 11:54
-
Close it, newbie mistake.Thanks! – Adrian Stamin Sep 26 '12 at 13:39
5 Answers
Look into the Runtime.addShutdownHook() method. http://docs.oracle.com/javase/6/docs/api/java/lang/Runtime.html#addShutdownHook%28java.lang.Thread%29

- 1,557
- 2
- 17
- 30
take a look of this may its helps you. Closing an Application
You can give your own implementation if some one press close button.
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.addWindowListener( new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
// Here you can give your own implementation according to you.
}
});

- 15,743
- 6
- 59
- 89
-
I was close.I just wrote new windowAdapter without adding it.Didn't realize.Thanks man! – Adrian Stamin Sep 26 '12 at 13:34
Simply add a WindowListener to your JFrame and use the event windowClosing

- 47,259
- 4
- 83
- 117
Sounds like you want to call addWindowListener
with a WindowListener
which handles windowClosing
or windowClosed
. You may well want to create a subclass of WindowAdapter
so you can just override the method(s) you're interested in.
Don't forget that your communication with the server should be in a different thread - don't block the UI thread with network traffic. However, also bear in mind that if your whole application is closing:
- Any connection to the server will close anyway
- Any background threads will be terminated

- 1,421,763
- 867
- 9,128
- 9,194
JFrame f = new JFrame("Blah");
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
//do whatever you want before the window closes.
}
});
f.setVisible(true);
Don't do f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
because that might interrupt your server communications. Instead, say System.exit(0)
manually when you have done your server communications.

- 7,356
- 12
- 48
- 71