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 TemplateGraphicsApplication extends Frame {     public TemplateGraphicsApplication()     {         super("Template Graphics App");         setResizable(false);         setLayout(null);              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.

Note 

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.



Java 1.4 Game Programming
Java 1.4 Game Programming (Wordware Game and Graphics Library)
ISBN: 1556229631
EAN: 2147483647
Year: 2003
Pages: 237

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net