Previous | Next | Trail Map | Creating a User Interface (with Swing) | Using Components, the GUI Building Blocks

Writing an Adjustment Listener

Adjustment events notify you of changes in the value of components that implement the Adjustable(in the API reference documentation) interface. Adjustable objects have an integer value, and they generate adjustment events whenever that value changes. The only AWT class that implements Adjustable is Scrollbar.

There are five kinds of adjustment events:

track
The user explicitly adjusted the value of the component. For a scrollbar, this might be the result of the user dragging the scrollbar knob.
unit increment, unit decrement
The user indicated the wish to slightly adjust the value of the component. For a scrollbar, this might be the result of the user clicking once on an up arrow or down arrow in the scrollbar.
block increment, block decrement
The user indicated the wish to adjust the value of the component by a larger amount. For a scrollbar, this might be the result of the user clicking once just above the down arrow or just below the up arrow.

Adjustment Event Methods

The AdjustmentListener interface contains a single method, and thus has no corresponding adapter class. Here's the method:
void adjustmentValueChanged(AdjustmentEvent)
Called by the AWT just after the listened-to component's value changes.

Examples of Handling Adjustment Events

Here is the adjustment event handling code from the Converter program, which uses two scrollbars to let the user set values:
class ConversionPanel ... implements AdjustmentListener ... {
    ...
    Scrollbar slider;
    ...
    ConversionPanel(...) {
        ...
        slider.addAdjustmentListener(this);
    }
    ...
    /** Respond to the slider. */
    public void adjustmentValueChanged(AdjustmentEvent e) {
        textField.setText(String.valueOf(e.getValue()));
        controller.convert(this);
    }
    ...
}
You can find entire program in Converter.java.

The AdjustmentEvent Class

The adjustmentValueChanged method has a single parameter: an AdjustmentEvent(in the API reference documentation) object. The AdjustmentEvent class defines the following handy methods:
Adjustable getAdjustable()
Returns the component that generated the event. You can use this instead of the getSource method.
int getAdjustmentType()
Returns the type of adjustment that occurred. The returned value is one of the following constants defined in the AdjustmentEvent class: UNIT_INCREMENT, UNIT_DECREMENT, BLOCK_INCREMENT, BLOCK_DECREMENT, TRACK.
int getValue()
Returns the value of the component just after the adjustment occurred.


Previous | Next | Trail Map | Creating a User Interface (with Swing) | Using Components, the GUI Building Blocks