ptg7068951
Change Listeners 223
To create a vertical slider, use a constructor with an additional first argu-
ment: the orientation of the slider. This argument should be the class vari-
able JSlider.VERTICALor JSlider.HORIZONTAL.
The following statement creates a vertical slider for a number from 1 to
1,000:
JSlider guess = new JSlider(JSlider.VERTICAL, 1, 1000, 500);
This slider starts with the caret—the part of the component that selects a
number—at the 500 position.
To display a label for a slider, you must set up the information the label
will contain. Call the slider’s setMajorTickSpacing(int)and
setMinorTickSpacing(int)methods to determine how often a tick mark is
displayed on the label. Major ticks are displayed as a thicker line than minor
ticks.
After you have set up how often tick marks appear, call the slider’s
setPaintTicks(boolean)method with trueas the argument. You also
can display the numeric value of each major tick by calling the slider’s
setPaintLabels(boolean)method with true.
Change Listeners
To monitor slider input, you must have a class that implements the
ChangeListenerinterfacein the javax.swing.eventpackage. This interface
includes only one method:
public voidstateChanged(ChangeEvent event); {
// statements to handle the event
}
To register an object as a change listener, call the addChangeListener(Object)
method of the container that holds the slider. When the slider is moved, the lis-
tening object’s stateChanged()method is called.
This method is called with a ChangeEventobject that can identify the slider
component that changed in value. Call the object’sgetSource()method
and cast the object to a JSlider, as in the following statement:
JSlider changedSlider = (JSlider) event.getSource();
In this example, eventis the ChangeEventobject that is an argument to the
stateChanged()method.