Creating Sliders Using JSlider Class

In this tutorial, you will learn how to use JSlider to create sliders in Java swing application.

A slider is a widget which allows user to input value by moving an indicator in vertical or horizontal fashion. User can also click on points to change the current value. To create a slider in swing you use JSlider class.  The JSlider class enables to create a slider with two types of tick marks: minor and major. The minor tick mark is shorter than major tick mark.

Here are the constructors of JSlider class:

ConstructorsDescription
public JSlider ()Creates a horizontal slider in a range of 0 and 100, the initial value is 50.
public JSlider (int orientation)Creates a horizontal slider with a given orientation.
public JSlider(int orient)Creates a progress bar with a given orientation determined byJSlider.VERTICAL or JSlider.HORIZONTAL.
public JSlider(int min, int max)Creates a horizontal slider with a given minimum and maximum values. The initial value is average of min plus max.
public JSlider(int orientation, int minimum, int maximum, int value)Creates a slider with the given orientation and the initialized minimum, maximum, and initial values.
public JSlider(BoundedRangeModel model)Create a horizontal slider with a given instance of BoundedRangeModel.

 Example of creating a simple slider

In this example, we will create a very simple slider.

JSlider Demo
package jsliderdemo;

import java.awt.*;
import javax.swing.*;

public class Main {

    public static void main(String[] args) {
        final JFrame frame = new JFrame("JSlider Demo");

        // create a slider
        JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 40, 10);
        slider.setMinorTickSpacing(5);
        slider.setMajorTickSpacing(20);
        slider.setPaintTicks(true);
        slider.setPaintLabels(true);
        slider.setLabelTable(slider.createStandardLabels(10));

        //
        frame.setLayout(new FlowLayout());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 200);
        frame.getContentPane().add(slider);
        frame.setVisible(true);
    }
}Code language: JavaScript (javascript)