Closing a Window

The setDefaultCloseOperation method was introduced to Swing as an easy way of specifying a default operation on a frame when the user attempts to close it. Other available constants for this method are DO_ NOTHING_ON_CLOSE, HIDE_ON_CLOSE, and DISPOSE_ON_CLOSE. The difference between EXIT_ON_CLOSE and DISPOSE_ON_CLOSE is that EXIT_ON_CLOSE will call the System.exit method, which will terminate your entire program, whereas DISPOSE_ON_CLOSE will hide and then dispose of your frame only; any other independent parts of your program will remain active. By default, the AWT Frame will do nothing when the user attempts to close the window, whereas a Swing JFrame will hide itself. We know how to change this for the JFrame, but for the AWT Frame we can use a WindowAdapter, as follows.

import java.awt.*;
import java.awt.event.*;
public class TemplateGraphicsapp extends Frame
 public TemplateGraphicsapp()
 super("Template Graphics App");
 addWindowListener(new WindowAdapter(){
 public void windowClosing(WindowEvent e) {
 System.exit(0); }
 // The rest of the code as before

First you will notice that we no longer need to include the package javax.swing and have also included the package java.awt.event. The package java.awt.event contains classes used for handling events, such as the window closing, as we have used above. This code may look a little strange, but we will discuss in detail using listeners and their adapter classes in the next chapter when we discuss the mouse and keyboard. After you have read the next chapter, it is advised that you look back upon this code; you should then be able to understand it fully. For now, however, we must move on.


Adding a window listener can be used with a Swing JFrame also. If both this method and a default close operation are specified, the listener method windowClosing will first be invoked followed by the default close operation.