Previous | Next | Trail Map | Creating a User Interface | Using the JFC/Swing Packages

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 16 image files in the example-swing/images directory that begin with "burger". To get the image files, you can download the swing lesson.
    See Getting Started with Swing if you need help compiling and running the application.
  2. Use the slider to adjust the animation speed.

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);
	        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.

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 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.

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 deals primarily with Fine Tuning the Slider's Appearance.

Fine Tuning the Slider's Appearance
Method Purpose
void setValue(int)
int getValue()
Set or get the slider's current value. The slider's knob is positioned here.
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 inverted 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.

Examples that Use JSlider

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.


Previous | Next | Trail Map | Creating a User Interface | Using the JFC/Swing Packages