Trail: Creating a GUI with JFC/Swing
Lesson: Writing Event Listeners
Section: Implementing Listeners for Commonly Handled Events
How to Write a Component Listener
Home Page > Creating a GUI with JFC/Swing > Writing Event Listeners
How to Write a Component Listener
The Component listener is a listener interface for receiving component events. A component is an object having a graphical representation that can be displayed on the screen and that can interact with the user. Some of the examples of components are the buttons, checkboxes, and scrollbars of a typical graphical user interface.

The class that is interested in processing a component event either implements this interface and all the methods it contains, or extends the abstract ComponentAdapter class overriding only the methods of interest. The listener object created from that class is then registered with a component using the component's addComponentListener method. When the component's size, location, or visibility changes, the relevant method in the listener object is invoked, and the ComponentEvent is passed to it.

One or more component events are fired by a Component object just after the component is hidden, made visible, moved, or resized.

The component-hidden and component-shown events occur only as the result of calls to a Component 's setVisible method. For example, a window might be miniaturized into an icon (iconified) without a component-hidden event being fired.

To write a simple Component listener program, follow the steps mentioned below:

The Component Listener API

The ComponentListener Interface

All of these methods are also in the adapter class, ComponentAdapter.
Method Purpose
componentHidden(ComponentEvent) Called after the listened-to component is hidden as the result of the setVisible method being called.
componentMoved(ComponentEvent) Called after the listened-to component moves, relative to its container. For example, if a window is moved, the window fires a component-moved event, but the components it contains do not.
componentResized(ComponentEvent) Called after the listened-to component's size (rectangular bounds) changes.
componentShown(ComponentEvent) Called after the listened-to component becomes visible as the result of the setVisible method being called.

The ComponentEvent Class

Method Purpose
Component getComponent() Returns the component that fired the event. You can use this instead of the getSource method.

Examples that Use Component Listeners

The following table lists the examples that use component listeners.

Example Where Described Notes
ComponentEventDemo This section Reports all component events that occur on several components to demonstrate the circumstances under which component events are fired.

Previous page: How to Write a Change Listener
Next page: How to Write a Container Listener