Java Tips Weblog

  • Blog Stats

    • 1,281,967 hits
  • Categories

  • Archives

Closing an Application

Posted by Rob Camick on May 1, 2009

I’m sure the users are having a great time using your application but as we all know, “all good things must come to an end“, so at some time the user is going to close the application. The user will generally have three ways to close an application:

  • click on the “Close” button of the frame
  • select the “Close” item from the sytem menu
  • select the “Exit” item that is typically found in the “File” menu of the application

You may have some application specific “close processing” such as:

  • prompting the user to confirm closing of the application
  • saving application properties to be used the next time the application starts

So how do you ensure that close processing is done no matter how the application is closed?

Well, we need to understand what happens when a user attempts to close a frame. First, any WindowListener that has been added to the frame will be invoked. In particular the windowClosing event will be fired to indicate the intention to close the frame. Secondly, the JFrame will handle the close request based on the property set by invoking the setDefaultCloseOperation(…) method of the frame. The values of this property are:

  • DO_NOTHING_ON_CLOSE – Don’t do anything
  • HIDE_ON_CLOSE (default) – Automatically hide the frame
  • DISPOSE_ON_CLOSE – Automatically hide and dispose the frame. When this is the only frame in the application the VM will also be terminated.
  • EXIT_ON_CLOSE – Exit the application using the System.exit method (only valid on a JFrame, not a JDialog)

Therefore you need to manage the default close operation of the frame and implement some action for the windowClosing event of the WindowListener. A simple implementation that prompts the user to confirm the closing of the frame might be something like:

frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

frame.addWindowListener( new WindowAdapter()
{
    public void windowClosing(WindowEvent e)
    {
        JFrame frame = (JFrame)e.getSource();

        int result = JOptionPane.showConfirmDialog(
            frame,
            "Are you sure you want to exit the application?",
            "Exit Application,
            JOptionPane.YES_NO_OPTION);

        if (result == JOptionPane.YES_OPTION)
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
});

Or, to make this process easier, so you don’t have to write a custom WindowListener for every application, you can use the CloseListener class. It provides support for the following functions:

  • displaying a dialog asking the user to confirm application closing
  • invoking a “Close Action” to perform some final processing before the frame is closed. The close action is only invoked if the application closing is confirmed.
  • setting the default close operation to the appropriate value. The default would be to use “exit”. This can be changed to “dispose” by using the setDisposeOnClose() method. If the application closing is not confirmed then it will be set to “do nothing”.

You can create the CloseListener class using 3 different constructors:

  • with a close message
  • with a close action
  • with a close message and a close action

To create a CloseListener that displays a close message in a confirm dialog you would use code like the following:

CloseListener cl = new CloseListener(
    "Are you sure you want to exit the application",
    "Exit Application");
JFrame frame = new JFrame("Closing an Application");
frame.addWindowListener( cl );

When the application is closed, you will see the following:

closing-an-application

To create a CloseListener that invokes a close Action you can extend AbstractAction and implement the actionPerformed(…) method. For example:

Action ca = new AbstractAction()
{
	public void actionPerformed(ActionEvent e)
	{
		JFrame frame = (JFrame)e.getSource();
		System.out.println("Closing: " + frame.getTitle());
	}
};

CloseListener cl = new CloseListener(ca);

JFrame frame = new JFrame("Closing an Application");
frame.addWindowListener( cl );

Obviously, the close action will be different for most applications so I’ll let you experiment with writing your own.

At the start I said there where three general ways to close an application. I’ve only discussed two of these above. So I’m sure you can’t wait any longer to hear about using an “Exit” menu item to close the application. Well, this is not part of a frame and must be added to any JMenuBar and JMenu you create for your application. To handle this you can use the ExitAction class. You simply create this class and then use it when creating a JMenuItem. When the menu item is invoked the action generates a windowClosing event that is dispatched to the frame. Once the event is dispatched, processing is the same as described above.

The code to use the ExitAction would be something like:

JMenu menu = new JMenu( "File" );
menu.add( ... );
ExitAction ea = new ExitAction();
ea.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("control X"));
menu.add( new JMenuItem( ea ) );

Setting a value for the accelerator key will allow you to close the frame by entering CTRL-X from the keyboard. CTRL-X will be added as the accelerator for the menu item that is created when using the ExitAction.

Note, an Action can also be used when creating a JButton. So the ExitAction can also be used to add a button to your frame.

Hopefully, using these two classes will make closing an application easier to implement. Although most of the discussion was geared towards a JFrame, the concepts still apply to a JDialog.

Get The Code

CloseListener.java
ExitAction.java

Related Reading

Java Tutorials: How to Write a Window Listener
Java Tutorials: How to Use Actions
Java API: javax.swing.JFrame.setDefaultCloseOperation

About these ads

14 Responses to “Closing an Application”

  1. Garratt said

    Nice classes, I’m loving reading all these posts and using bits and pieces of code.

    However this erks me:
    return (result == JOptionPane.YES_OPTION) ? true : false;

    I guess it helps newbies understand the super IF statement?, but it’s the same as saying:
    return (result == JOptionPane.YES_OPTION);

    Keep up the good work guys :)

    • Rob Camick said

      Actually, I’m not sure what I was thinking, I usually code it the way you suggested. Just a brain cramp I guess.

      • Garratt said

        :) happens…
        On another note, is there anyway to set different settings for closing the application via the system menu? Heaven forbid our application seized up, would be nice to still have the option to right-click close without getting a confirmation dialog.

      • Garratt said

        I mean of course the windows taskbar in windows. I’m pretty sure the kill command works perfectly fine for those in unix.

      • Rob Camick said

        I guess thats what makes this a good general solution. All ways of closing the program go through the same code, so you always get the popup. However, I noticed that if you use Ctrl+Alt+Delete to kill the application, you still get the popup, but a few seconds later you get a Windows dialog to kill the application. So you don’t need to respond to the confirmation dialog.

  2. chris said

    Thanks for this useful post about closing an Swing application.. I was looking for a clean solution to implement a MenuItem that would close my application. Some other posts recommended using System.out.exit(0) but your solution is much cleaner. It allows me to clean up some resources and save important data before shutting down the application by using a WindowListener.

  3. Rob Camick said

    Yes, using a WindowListener is much more flexible. Thanks for the feedback.

  4. Anonymous said

    thanks buddy…

  5. Anonymous said

    Keep up the good work guys :)

  6. Anonymous said

    just started with java …. was a usefull blog, thx

  7. Anonymous said

    where do you place it. I’m new.

  8. Anonymous said

    Thanks! This was very helpful.

  9. trang said

    Thanks! This was very helpful for me.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.

Join 97 other followers

%d bloggers like this: