The JavaTM Tutorial

| 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 or dialog) 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) for an example of a handler for window-closing events. Within that section, Responding to Window-Closing Events 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`.

> 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` interface and its corresponding adapter class, `WindowAdapter`, 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` 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) | 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 | Disposes a frame displayed by an applet when the user closes the frame.
> `SliderDemo` | How to Use Sliders | 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 | Contains a text pane that requests the keyboard focus in response to window-activated events.
> `DialogDemo` and `CustomDialog.java` | General Rules for Using Text Components | Uses `setDefaultCloseOperation` instead of a window listener to determine what action to take when the user closes the window.

| Start of Tutorial > Start of Trail > Start of Lesson | Search Feedback Form