By Tony Bevis on Thursday, 19 October 2023
Category: Java

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:


The default slider will look like this:

​ 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:

The slider will now look as follows:

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

Enter your text here ...


Your slider will now look like this:

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

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

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.

  Which results in this:

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

Next lesson:14.10 JSpinner

Related Posts

Leave Comments