Exiting a Program
Home ] Up ] Your First Frame ] Sizing a Frame ] Positioning a Frame ] [ Exiting a Program ] A Centered Frame ]

 

 

If you were trying out the above Java programs, and were particularly observant while you ran the programs, you may have noticed a peculiarity when you tried to close the frame (i.e., clicked on the 'x' on the right side of the title bar, or clicked on the icon on the left side of the title bar, and selected Close on the resulting menu).  

When you close the frame, it becomes invisible, but the program is still running!  Why is this?

It turns out that you can choose what a JFrame should do when you close it.  The choices are:

Constant Defined Description
DO_NOTHING_ON_CLOSE javax.swing.WindowConstants Don't do anything; require the program to handle the operation in the windowClosing method of a registered WindowListener object.
HIDE_ON_CLOSE
(the default)
javax.swing.WindowConstants Automatically hide the frame after invoking any registered WindowListener objects.
DISPOSE_ON_CLOSE javax.swing.WindowConstants Automatically hide and dispose the frame after invoking any registered WindowListener objects.
EXIT_ON_CLOSE javax.swing.JFrame
and
javax.swing.WindowConstants
Exit the application using the System.exit method. Use this only in applications.

For the moment, don't worry about those references to windowClosing method and WindowListener objects.  We'll get to those when we talk about Java events.

So, to specify that closing the frame should also exit the program, you have to specify it explicitly:

package swingExamples;

import javax.swing.JFrame;

public class ExitingFrame extends JFrame
{
  public ExitingFrame()
  {
    setTitle("ExitingFrame");
    setBounds(100, 200, 300, 200);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
  }
  
  public static void main(String[] args)
  {
    ExitingFrame frame = new ExitingFrame();
    frame.setVisible(true);
  }
}

which produces this equally stunning result:

But at least you can tell it to exit!

 

 

This page was last modified on 02 October, 2007