Swing JFrame close button handlers

When a JFrame’s close button (the “X” button in Windows) is pressed, the JFrame closes, but program continues running in the background. Plus, this doesn’t give you an opportunity to do the classic, “You haven’t saved! Do you really want to quit?” type of prompt. There are several ways you can accomplish these goals.

Custom WindowListener

You can add a WindowListener to your JFrame. For example:

class MyWindowListener implements WindowListener
{
    public void windowClosing(WindowEvent arg0)
    {
        [DO STUFF HERE]
        System.exit(0);
    }

    public void windowOpened(WindowEvent arg0)
    {
    }

    public void windowClosed(WindowEvent arg0)
    {
    }

    public void windowIconified(WindowEvent arg0)
    {
    }

    public void windowDeiconified(WindowEvent arg0)
    {
    }

    public void windowActivated(WindowEvent arg0)
    {
    }

    public void windowDeactivated(WindowEvent arg0)
    {
    }
}

Then just add the following code to your JFrame:


someJFrame.addWindowListener(new MyWindowListener());


WindowAdapter

If you only really want to override the windowClosing function, you can instead create an anonymous class the extends WindowAdapter (which already implements WindowListener). For example:

someJFrame.addWindowListener(new WindowAdapter()
{
        public void windowClosing(WindowEvent _closeEvent)
        {
            [DO STUFF HERE]
            System.exit(0);
        }
}
);

Window close event

This is the quick-and-dirty method (and really the most common). There are four basic “on-close” operations that can be easily set and used. The four operations are:

  1. DO_NOTHING_ON_CLOSE: Does nothing! A WindowListener’s windowClosing method will still be triggered, but the JFrame won’t do anything on its own.
  2. HIDE_ON_CLOSE: This is the default for JDialog and JFrame. Simply hides the window. The window can be re-displayed later.
  3. DISPOSE_ON_CLOSE: This is the default for JInternal Frame. Removes the window and releases its resources.
  4. EXIT_ON_CLOSE: Exits the application using System.exit(0).

The call to configure the close operation is as follows:


someJFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

Published in: on 12/18/2009 at 13:34  Leave a Comment  
Tags: , ,