Java: Sliders


A slider (JSlider class) lets the user easily select from a range of integer values. Use sliders for integer input whenever you can. They are easier for the user than text fields, and there is no possibility of illegal input values, so your programming is simpler.


The usual constructor is
   JSlider s = new JSlider(orientation, min, max, initial);
JSlider sl = new JSlider(JSlider.HORIZONTAL, 0, 20, 10);

Tick Marks

You can add both major and minor tick marks. You must call setPaintTicks(true) to make the tick marks appear. Here is an example that sets major tick marks every 10 values and minor tick marks every 1 value:
   sl.setMajorTickSpacing(10); // sets numbers for biggest tick marks
   sl.setMinorTickSpacing(1);  // smaller tick marks
   sl.setPaintTicks(true);     // display the ticks


To display the values next to the major tick marks:

Listeners and getting the slider value

See Change Listener to see how to do something when the slider is changed.

Advanced Appearance

In addition to tick marks, you can specify text or icon labels at any values that you specify using setLabelTable(...). You can also specify which end of the slider should have the high or low values using setInverted(true/false).