views:

256

answers:

3

Hi,

I am working on a chat client using a socket, and I want a certain code to be executed before the window closes when the user clicks on "X" (like closing the connection properly).

Can I do that without having to implement all the abstract methods in WindowListener?

/Avin

+3  A: 

Just extend WindowAdapter, rather than implement WindowListener.

You'll find this concept at all Swing listeners. (MouseListener/MouseAdapter, KeyListener/KeyAdapter, ...) There is a Listener interface and an Adapter class which implements this interface with empty methods.

So if you want to react only to a specific event use the adapter and override the desired method.

Example:

setWindowListener(new WindowAdapter() {
    public void windowClosed(WindowEvent e) {
        //Cleanup code
    }
});
DR
That seems to be working fine. Thanks a lot.
Aveen
+1  A: 

Here is what you need

private class Closer extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
int exit = JOptionPane.showConfirmDialog(this, "Are you
sure?");
if (exit == JOptionPane.YES_OPTION) {
System.exit(0);}
}
}
DaDa
A: 

Example of how to add an ExitListener from within a FrameView :

YourApp.getApplication().addExitListener(new ExitListener() {

         @Override
         public boolean canExit(EventObject arg0) {
            doStuff();

            // the return value is used by the application to actually exit or
            // not. Returning false would prevent the application from exiting.
            return true;
         }
}
JRL