Java programming course: 14.9 JSlider


JSlider

The JSlider class allows the user to select a value, from within a range of values, by moving a sliding knob:

JSlider slider = new JSlider();
panel.add(slider);
 
  • By default, the allowable range of values is from 0 to 100, with the knob pre-selected at 50.

The default slider will look like this:

JSlider

You can use your mouse to drag the slider to a new position. To make the slider more useful you can paint tick marks and labels at predefined gaps. For example, to place labels every 10 units add the following statements:

slider.setMajorTickSpacing(10);
slider.setPaintLabels(true);
slider.setPaintTicks(true);
 

The slider will now look as follows:

JSlider with tick marks

If your slider needs a different range and starting value, you can use a different constructor:

JSlider slider = new JSlider(0, 250, 50);
slider.setMajorTickSpacing(50); // *** NOTE CHANGED TO 50 ***
 

Enter your text here ...

  • The first constructor argument is the minimum allowed value
  • The second constructor argument is the maximum allowed value
  • The third constructor argument is the initial value. Note that this argument is optional, and if not supplied then the initial value will be halfway between the minimum and maximum values
  • Note also the major tick spacing has been changed

Your slider will now look like this:

JSlider with alternate tick marks

You can also specify minor tick spaces to appear between the major tick spaces:

slider.setMinorTickSpacing(25); 

Now the slider will label the major tick spaces every 50 units, as before, but in addition will show minor ticks every 25 units:

JSlider with major and minor tick marks

While the default orientation is horizontal, as shown in the above examples, you can place the slider vertically using the setOrientation() method[1]:

[1] You can also set the orientation using an alternative constructor – see the Javadoc API.
slider.setOrientation(JSlider.VERTICAL); 

  Which results in this:

Vertical JSlider

To obtain the selected value use the getValue() method:

int value = slider.getValue(); 


Print
×
Stay Informed

When you subscribe, we will send you an e-mail whenever there are new updates on the site.

Related Posts

 

Comments

No comments made yet. Be the first to submit a comment
Thursday, 11 December 2025

Captcha Image