2

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.

Sumit Singh
  • 15,743
  • 6
  • 59
  • 89
Adrian Stamin
  • 687
  • 2
  • 8
  • 21

5 Answers5

5

Look into the Runtime.addShutdownHook() method. http://docs.oracle.com/javase/6/docs/api/java/lang/Runtime.html#addShutdownHook%28java.lang.Thread%29

Billdr
  • 1,557
  • 2
  • 17
  • 30
5

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.
     }
  });
Sumit Singh
  • 15,743
  • 6
  • 59
  • 89
4

Simply add a WindowListener to your JFrame and use the event windowClosing

Guillaume Polet
  • 47,259
  • 4
  • 83
  • 117
3

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
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
3
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.

11684
  • 7,356
  • 12
  • 48
  • 71