Next page | Contents page |

Exercise 23 - a window

Compile and run this program and note everything it can do.

public class Window extends javax.swing.JFrame
{
    public Window (String title)
    {
       super (title);
    } // Window

    public static void main (String [] args)
    {
       Window w = new Window ("Window");
       w.setSize (400, 200);
       w.setLocation (100, 100);
       w.setVisible (true);
    } // main

} // Window

Closing the window

You should have seen that a command window was left running when the application window was closed. In fact the JVM was not stopped (there are 2 threads!). Improve by adding this before w.setVisible (); in main:

	w.addWindowListener    // Handle window close requests
	(
		new WindowAdapter ()
		{
			public void windowClosing (WindowEvent ev)
			{ 
				System.exit (0);  // Exit app with OK status
			}
		}
	);  

This implements an adapter class "on the fly" as an anonymous inner class.

Alternatively, in Java 1.3 onwards there is also, for a JFrame,

    w.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
Next page | Contents page |