The JavaTM Tutorial

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

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

## How to Write a Change Listener

> Change events occur whenever a component changes state. For example, a button fires a change event every time the button is pressed. The look-and-feel implementation of the button listens for change events so that it can react appropriately to the state change (repainting itself, for example). Although nothing's stopping you from registering for change events on a button, most programs don't need to do so.

> Two Swing components rely on change events for basic functionality -- sliders and color choosers. To learn when the value in a slider changes, you need to register a change listener. Similarly, you need to register a change listener on a color chooser to be informed when the user chooses a new color.

> Here is an example of change event handling code for a slider:

> >     //...where initialization occurs:
> >     framesPerSecond.addChangeListener(new SliderListener());
> >     ...
> >     class SliderListener implements ChangeListener {
> >         public void stateChanged(ChangeEvent e) {
> >             JSlider source = (JSlider)e.getSource();
> >             if (!source.getValueIsAdjusting()) {
> >                 int fps = (int)source.getValue();
> >     	    ...
> >             }
> >         }
> >     }

> This snippet is from a program named `SliderDemo`. You can find the source and image files for the program, along with instructions for compiling and running it, in How to Use Sliders.

### The Change Event API

> The `ChangeListener` interface has just one method, so it has no corresponding adapter class. Here's the method:
> `void stateChanged(ChangeEvent)`
>   Called when the listened-to component changes state.
> The `stateChanged` method has a single parameter: a `ChangeEvent` object. To get the component that fired the event, use the `getSource` method which `ChangeEvent` inherits from `EventObject`. The `ChangeEvent` class defines no additional methods.

### Examples that Use Change Listeners

> The following table lists the examples that use change listeners.

> Example | Where Described | Notes
> --- | --- | ---
> `SliderDemo` and `SliderDemo2` | How to Use Sliders | Registers a change listener on a slider that controls animation speed. The change listener ignores the change events until the user releases the slider.
> `ColorChooserDemo` and `ColorChooserDemo2` | Getting Started | Uses a change listener on the selection model of a color chooser to learn when the user changes the current color.
> `ConverterRangeModel`, and its subclass, `FollowerRangeModel` | The Anatomy of a Swing-Based Program | Implement custom models for the sliders used in the `Converter` demo. Both models explicitly fire change events when necessary.

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