Previous | Next | Trail Map | Creating a GUI with JFC/Swing | Using Swing Components

How to Use Sliders

Use a JSlider(in the API reference documentation) 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:


Try this:
  1. Compile and run the application. The source file is SliderDemo.java. You will also need the 14 image files in the example-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.
  2. Use the slider to adjust the animation speed.
  3. Push the slider to 0 to stop the animation.

Below is the code from SliderDemo.java that creates the slider in the previous example.
JSlider 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);
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 call setPaintTicks(true) (just calling setPaintTicks(true) is not enough). To display standard, numeric labels at major tick mark locations set the major tick spacing, then call setPaintLabels(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's ChangeListener is called, thereby changing the speed of animation:

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();
	    }
        }
    }
}
If you move the slider to zero, the animation stops.

Notice that the stateChanged method only changes the animation speed if getValueIsAdjusting returns false. 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 call setPaintLabels(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:
  1. 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 by SliderDemo.java.
  2. Create a Hashtable containing the value for each label and its position. Provide the hash table as an argument to setLabelTable. SliderDemo2.java, shown below, uses this technique:

    Here's the code from SliderDemo2.java that creates the slider in the program:

    //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));
    
    This code explicitly creates a Hashtable and populates it with positions and label values. Each label position must be an Integer. Each label value must be a Component 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 use JSlider's createStandardLabels method to create the Hashtable for you. You can also modify the table returned by createStandardLabels to then customize it.

The Slider API

The following tables list the commonly used JSlider constructors and methods. Other methods you're likely to call are defined by the JComponent(in the API reference documentation) and Component(in the API reference documentation) 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 or JSlider.VERTICAL. The last three int arguments, when present, specify the slider's minimum, maximum, and initial values, respectively.
JSlider( BoundedRangeModel(in the API reference documentation)) 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 or JSlider.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 use JSlider 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.


Previous | Next | Trail Map | Creating a GUI with JFC/Swing | Using Swing Components