The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Creating a GUI with JFC/Swing
Lesson: Writing Event Listeners

How to Write a Window Listener

Window events are fired by a window (such as a frame(in the Creating a GUI with JFC/Swing trail) or dialog(in the Creating a GUI with JFC/Swing trail)) just after the window is opened, closed, iconified, deiconified, activated, or deactivated. Opening a window means showing it for the first time; closing it means removing the window from the screen. Iconifying it means substituting a small icon on the desktop for the window; deiconifying means the opposite. A window is activated if it or a component it contains has the keyboard focus; deactivation occurs when the window and all of its contents lose the keyboard focus. If you want to be notified when a window is made visible or hidden, then you should register a component listener on the window.

The most common use of window listeners is implementing custom window-closing behavior. For example, you might use a window listener to save data before closing the window, or to exit the program when the last window closes.

You don't necessarily need to implement a window listener to specify what a window should do when the user closes it. By default, when the user closes a window the window becomes invisible. You can specify different behavior -- disposing of the window, for example -- using the JFrame or JDialog setDefaultCloseOperation method. If you decide to implement a window-closing handler, then you might want to use setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE) to specify that your window listener takes care of all window-closing duties.

See How to Make Frames (Main Windows)(in the Creating a GUI with JFC/Swing trail) for an example of a handler for window-closing events. Within that section, Responding to Window-Closing Events(in the Creating a GUI with JFC/Swing trail) has details on how to use setDefaultCloseOperation.

Another common use of window listeners is to stop threads and release resources when a window is iconified, and to start up again when the window is deiconified. This way, you can avoid unnecessarily using the processor or other resources. For example, when a window that contains animation is iconified, it should stop its animation thread and free any large buffers. When the window is deiconified, it can start the thread again and recreate the buffers.

The following applet demonstrates window events. By clicking the top button in the applet, you can bring up a small window. The controlling class listens for window events from the window, displaying a message whenever it detects a window event. You can find the applet's code in WindowEventDemo.java(in a .java source file).

Click this figure to run the applet.
This is a picture of the applet's GUI. To run the applet, click the picture. The applet will appear in a new browser window.


Try this: 
  1. Bring up the Window Demo Window by clicking the applet's top button.
    The first time you click this button, you'll see a "Window opened" message in the applet's display area.
  2. Click the window if it doesn't already have the focus.
    Do you see a "Window activated" message in the applet's display area?
  3. Iconify the window, using the window controls.
    You'll see a "Window iconified" message in the applet's display area.
  4. Deiconify the window.
    You'll see a "Window deiconified" message in the applet's display area.
  5. Close the window, using the window controls.
    You'll see "Window closing" in the applet's display area. Because the window-closing event handler invokes setVisible(false) instead of dispose(), you won't see "Window closed".

Here is the applet's window event handling code:

public class WindowEventDemo ... implements WindowListener {
     ...//where initialization occurs:
        //Create but don't show window.
        window = new JFrame("Window Event Window");
        window.addWindowListener(this);
        window.getContentPane().add(
	    new JLabel("The applet listens to this window "
                       + "for window events."),
	    BorderLayout.CENTER);
        window.pack();
    }

    public void windowClosing(WindowEvent e) {
        window.setVisible(false);
        displayMessage("Window closing", e);
    }

    public void windowClosed(WindowEvent e) {
        displayMessage("Window closed", e);
    }

    public void windowOpened(WindowEvent e) {
        displayMessage("Window opened", e);
    }

    public void windowIconified(WindowEvent e) {
        displayMessage("Window iconified", e);
    }

    public void windowDeiconified(WindowEvent e) {
        displayMessage("Window deiconified", e);
    }

    public void windowActivated(WindowEvent e) {
        displayMessage("Window activated", e);
    }

    public void windowDeactivated(WindowEvent e) {
        displayMessage("Window deactivated", e);
    }

    void displayMessage(String prefix, WindowEvent e) {
        display.append(prefix
                       + ": "
                       + e.getWindow()
                       + newline); 
    }
    ...
}

The Window Event API

The WindowListener(in the API reference documentation) interface and its corresponding adapter class, WindowAdapter(in the API reference documentation), contain these methods:

void windowOpened(WindowEvent)
Called just after the listened-to window has been shown for the first time.

void windowClosing(WindowEvent)
Called in response to a user request that the listened-to window be closed. To actually close the window, the listener should invoke the window's dispose or setVisible(false) method.

void windowClosed(WindowEvent)
Called just after the listened-to window has closed.

void windowIconified(WindowEvent)
void windowDeiconified(WindowEvent)
Called just after the listened-to window is iconified or deiconified, respectively.

void windowActivated(WindowEvent)
void windowDeactivated(WindowEvent)
Called just after the listened-to window is activated or deactivated, respectively.
Each window event method has a single parameter: a WindowEvent(in the API reference documentation) object.
Window getWindow()
Returns the window that fired the event. You can use this instead of the getSource method.

Examples that Use Window Listeners

The following table lists the examples that use window listeners.

Example Where Described Notes
WindowEventDemo This section Reports all window events that occur on one window to demonstrate the circumstances under which window events are fired.
FrameDemo How to Make Frames (Main Windows)(in the Creating a GUI with JFC/Swing trail) One of many examples that listens for window closing events, so that the application can exit when its only window is closed.
ComponentEventDemo How to Write a Component Listener Listens for window-closing events on a frame displayed by an applet. This way, the applet knows whether to re-open the window when the user leaves and returns to the applet's page.
FlowWindow How to Use FlowLayout(in the Creating a GUI with JFC/Swing trail) Disposes a frame displayed by an applet when the user closes the frame.
SliderDemo How to Use Sliders(in the Creating a GUI with JFC/Swing trail) Listens for window iconify and deiconify events, so that it can stop the animation when the window isn't visible.
InternalFrameEventDemo How to Write an Internal Frame Listener Reports all internal frame events that occur on one internal frame to demonstrate the circumstances under which internal frame events are fired. Internal frame events are similar to window events.
TextComponentDemo General Rules for Using Text Components(in the Creating a GUI with JFC/Swing trail) Contains a text pane that requests the keyboard focus in response to window-activated events.
DialogDemo and
CustomDialog.java(in a .java source file)
General Rules for Using Text Components(in the Creating a GUI with JFC/Swing trail) Uses setDefaultCloseOperation instead of a window listener to determine what action to take when the user closes the window.


Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2002 Sun Microsystems, Inc. All rights reserved.