The JFrame Class

The most common Swing container for Java applications is the JFrame class. Like java.awt.Frame, JFrame provides a top-level window with a title, border, and other platform-specific adornments (e.g., minimize, maximize, and close buttons). Because it uses a JRootPane as its only child, working with a JFrame is slightly different than working with an AWT Frame.

Exiting Frames

In many applications, closing the main application frame should cause the program to exit (shutting down the virtual machine). The default implementation, however, is only to hide the frame when it is closed, leaving the virtual machine running with no visible frame. We’ll briefly look at two simple ways to get the program to exit when the frame is closed.
 
The simplest thing to do is to set the close operation to exit:

import javax.swing.JFrame;

public class FrameClose1 {
  public static void main(String[] args) {
    JFrame mainFrame = new JFrame( );

    // Exit app when frame is closed.
    mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    mainFrame.setSize(320, 240);
    mainFrame.setVisible(true);
  }
}

Another alternative that works with SDKs prior to 1.3 is to add a WindowListener to the frame, calling System.exit( ) in the windowClosing( ) method. Here’s a simple example:

import javax.swing.JFrame;
import java.awt.event.*;

public class FrameClose2 {
  public static void main(String[] args) {
    JFrame mainFrame = new JFrame( );

    // Exit app when frame is closed.
    mainFrame.addWindowListener(new WindowAdapter( ) {
      public void windowClosing(WindowEvent ev) {
        System.exit(0);
      }
    });

    mainFrame.setSize(320, 240);
    mainFrame.setVisible(true);
  }
}

If you get tired of writing this same block of code in every frame that needs to close properly, you might want to use an extension of JFrame that supports this feature. Here’s one possible implementation of such a class:

import javax.swing.JFrame;
import java.awt.event.WindowEvent;

// A very simple extension of JFrame that defaults to EXIT_ON_CLOSE for
// its close operation. Relies on the 1.3 or higher SDK.
public class ExitFrame extends JFrame {

  public ExitFrame( ) {
    super( );
    setDefaultCloseOperation(EXIT_ON_CLOSE);
  }

  public ExitFrame(String title) {
    super(title);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
  }
}