Java Reference
In-Depth Information
This manner of listening for adjustment events works perfectly well. However, you may
prefer to attach a
ChangeListener
to the data model, as described next.
Listening to Scrolling Events with a ChangeListener
Attaching a
ChangeListener
to a
JScrollBar
data model provides more flexibility in your program
designs. With an AWT
AdjustmentListener
, listeners are notified only when the value of the
scrollbar changes. On the other hand, an attached
ChangeListener
is notified when there's any
change in the minimum value, maximum value, current value, or extent. In addition, because the
model has a
valueIsAdjusting
property, you can choose to ignore intermediate change events—
something you can also do with an
AdjustmentListener
, via the property of the same name in
the
AdjustmentEvent
.
To demonstrate, define a
ChangeListener
that prints out the current value of the scrollbar
when the model has finished adjusting, as shown in Listing 12-1. You'll enhance this
BoundedChangeListener
class throughout the chapter.
Listing 12-1.
ChangeListener for BoundedRangeModel
import javax.swing.*;
import javax.swing.event.*;
public class BoundedChangeListener implements ChangeListener {
public void stateChanged(ChangeEvent changeEvent) {
Object source = changeEvent.getSource();
if (source instanceof BoundedRangeModel) {
BoundedRangeModel aModel = (BoundedRangeModel)source;
if (!aModel.getValueIsAdjusting()) {
System.out.println ("Changed: " + aModel.getValue());
}
} else {
System.out.println ("Something changed: " + source);
}
}
}
Once you create the listener, you can create the component and attach the listener. In this
particular case, you need to attach the listener to the data model of the component, instead of
directly to the component.
ChangeListener changeListener = new BoundedChangeListener();
JScrollBar anotherJScrollBar = new JScrollBar (JScrollBar.HORIZONTAL);
BoundedRangeModel model = anotherJScrollBar.getModel();
model.addChangeListener(changeListener);
The source for the testing program is shown in Listing 12-2.