Java Reference
In-Depth Information
Handling JSlider Events
You track changes to a JSlider with a ChangeListener . There's no AdjustmentListener , as
there is with JScrollBar (and Scrollbar ). The same BoundedChangeListener from the earlier
JScrollBar example could be added to a data model of the JSlider , and you'll then be notified
when the model changes.
ChangeListener aChangeListener = new BoundedChangeListener();
JSlider aJSlider = new JSlider ();
BoundedRangeModel model = aJSlider.getModel();
model.addChangeListener(changeListener);
In addition to attaching a ChangeListener to the model, you can associate the ChangeListener
directly with the JSlider itself. This allows you to share the data model between views and
listen independently for changes. This requires you to modify the preceding listener a bit,
because the change event source will now be a JSlider instead of a BoundedRangeModel . The
updated BoundedChangeListener , shown in Listing 12-3, will work for both associations, however.
The changes are boldfaced in the following listing.
Listing 12-3. ChangeListener for BoundedRangeModel and JSlider
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 if (source instanceof JSlider) {
JSlider theJSlider = (JSlider)source;
if (!theJSlider.getValueIsAdjusting()) {
System.out.println ("Slider changed: " + theJSlider.getValue());
}
} else {
System.out.println ("Something changed: " + source);
}
}
}
The association with the slider can now be direct, instead of indirect through the model.
aJSlider.addChangeListener(changeListener);
Search WWH ::




Custom Search