简体   繁体   中英

How to use something other than the DefaultClosingOperation when closing a JFrame window?

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

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
    }
});

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);}
}
}

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;
         }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM