Using Swing Components |
Use aJSlider
to let the user enter a numeric value bounded by a minimum and maximum value. By using a slider instead of a text field, you eliminate input errors.Here's a picture of an application that uses a slider to control animation speed:
Below is the code from
Try this:
- Compile and run the application. The source file is
SliderDemo.java
. You will also need the 14 image files in theexample-swing/images/doggy
directory. To get the image files, you need to download the entire swing lesson.
See Getting Started with Swing if you need help.- Use the slider to adjust the animation speed.
- Push the slider to 0 to stop the animation.
SliderDemo.java
that creates the slider in the previous example.By default, spacing for major and minor ticks is zero. To see tick marks, you must explicitly set the spacing for either major or minor ticks (or both) to a non-zero value and callJSlider framesPerSecond = new JSlider(JSlider.HORIZONTAL, 0, 30, FPS_INIT); framesPerSecond.addChangeListener(new SliderListener()); framesPerSecond.setMajorTickSpacing(10); framesPerSecond.setMinorTickSpacing(1); framesPerSecond.setPaintTicks(true); framesPerSecond.setPaintLabels(true); framesPerSecond.setBorder(BorderFactory.createEmptyBorder(0,0,10,0)); . . . //add the slider to the content pane contentPane.add(framesPerSecond);setPaintTicks(true)
(just callingsetPaintTicks(true)
is not enough). To display standard, numeric labels at major tick mark locations set the major tick spacing, then callsetPaintLabels(true)
. The example program provides the labels for its slider this way. However, slider labels are highly configurable. See Providing Labels for Sliders for an example.When you move the slider, the
stateChanged
method of the slider'sChangeListener
is called, thereby changing the speed of animation:If you move the slider to zero, the animation stops.class SliderListener implements ChangeListener { public void stateChanged(ChangeEvent e) { JSlider source = (JSlider)e.getSource(); if (!source.getValueIsAdjusting()) { int fps = (int)((JSlider)e.getSource()).getValue(); if (fps == 0) { if (!frozen) stopAnimation(); } else { delay = 1000 / fps; timer.setDelay(delay); timer.setInitialDelay(delay * 4); if (frozen) startAnimation(); } } } }Notice that the
stateChanged
method only changes the animation speed ifgetValueIsAdjusting
returnsfalse
. Many change events are fired as the user moves the slider knob. This program is only interested in the final result of the user's action. For information about change listeners, refer to How to Write a Change Listener.Providing Labels for Sliders
To display labels on a slider, you must callsetPaintLabels(true)
and provide a set of labels that indicates the position and value for each label. A slider's labels can be specified using one of the following two techniques:
- Call
setMajorTickSpacing
with a non-zero value. Done in this manner, the labels identify the value at each major tick mark. This is the technique used bySliderDemo.java
.- Create a
Hashtable
containing the value for each label and its position. Provide the hash table as an argument tosetLabelTable
.SliderDemo2.java
, shown below, uses this technique:Here's the code from
SliderDemo2.java
that creates the slider in the program:This code explicitly creates a//Create the slider JSlider framesPerSecond = new JSlider(JSlider.VERTICAL, 0, 30, FPS_INIT); framesPerSecond.addChangeListener(new SliderListener()); framesPerSecond.setMajorTickSpacing(10); framesPerSecond.setPaintTicks(true); //Create the label table Dictionary labelTable = new Hashtable(); labelTable.put( new Integer( 0 ), new JLabel("Stop") ); labelTable.put( new Integer( 3 ), new JLabel("Slow") ); labelTable.put( new Integer( 30 ), new JLabel("Fast") ); framesPerSecond.setLabelTable( labelTable ); framesPerSecond.setPaintLabels(true); framesPerSecond.setBorder(BorderFactory.createEmptyBorder(0,0,0,10));Hashtable
and populates it with positions and label values. Each label position must be anInteger
. Each label value must be aComponent
and, in this program, are simply text labels. You can also use labels with icons for label values. If you want a set of numeric labels positioned at a specific interval, you can useJSlider
'screateStandardLabels
method to create theHashtable
for you. You can also modify the table returned bycreateStandardLabels
to then customize it.The Slider API
The following tables list the commonly usedJSlider
constructors and methods. Other methods you're likely to call are defined by theJComponent
andComponent
classes and include [PENDING: anything in particular for JSlider?]. [Link to JComponent and Component discussions.]The API for using sliders falls into these categories:
Creating a Slider Constructor Purpose JSlider()
Creates a horizontal slider with the range 0 to 100 and an initial value of 50. JSlider(int min, int max)
JSlider(int min, int max, int value)Creates a horizontal slider with the specified minimum and maximum values. The third int
argument, when present, specifies the slider's initial value.JSlider(int orientation)
JSlider(int orientation, int min, int max, int value)Creates a slider with the specified orientation, which must be either JSlider.HORIZONTAL
orJSlider.VERTICAL
. The last threeint
arguments, when present, specify the slider's minimum, maximum, and initial values, respectively.JSlider( BoundedRangeModel)
Creates a horizontal slider with the specified model, which manages the slider's minimum, maximum, and current values and their relationship.
Fine Tuning the Slider's Appearance Method Purpose void setValue(int)
int getValue()Set or get the slider's current value. This method also positions the slider's knob. void setOrientation(int)
int getOrientation()Set or get the orientation of the slider. Possible values are JSlider.HORIZONTAL
orJSlider.VERTICAL
.void setInverted(boolean)
boolean getInverted()Set or get whether the maximum is shown at the left of a horizontal slider or at the bottom of a vertical one, thereby inverting the slider's range. void setMinimum(int)
int getMinimum()
void setMaximum(int)
int getMaximum()Set or get the minimum or maximum values of the slider. Together, these methods set or get the slider's range. void setMajorTickSpacing(int)
int getMajorTickSpacing()
void setMinorTickSpacing(int)
int getMinorTickSpacing()Set or get the range between major and minor ticks. You must call setPaintTicks(true)
for the tick marks to appear.void setPaintTicks(boolean)
boolean getPaintTicks()Set or get whether tick marks are painted on the slider. void setLabelTable(Dictionary)
Dictionary getLabelTable()Set or get the labels for the slider. You must call setPaintLabels(true)
for the labels to appear.createStandardLabels
is a convenient method for creating a standard set of labels.void setPaintLabels(boolean)
boolean getPaintLabels()Set or get whether labels are painted on the slider. You set the labels with setLabelTable
or by setting major tick spacing.
Watching the Slider Operate Method Purpose void addChangeListener(ChangeListener)
[PENDING] boolean getValueIsAdjusting()
[PENDING] Examples that Use Sliders
This table shows the examples that useJSlider
and where those examples are described.
Example Where Described Notes SliderDemo.java
This page Shows a slider with labels at major tick marks. SliderDemo2.java
This page Shows a vertical slider with custom labels. Converter.java
The Anatomy of a Swing-Based Program Uses two sliders that share data and have a custom BoundedRangeModel
.
Using Swing Components |