How do I use a JSlider component?

This simple example show you how to use the JSlider component. A JSlider component is intended to let the user easily enter a numeric value bounded by a minimum and maximum value.

There are a couples properties that you need to set when creating a JSlider. These include setting setMinorTickSpacing(), setMajorTickSpacing(), setPaintTicks() and setPaintLabels(). These methods set the minor tick spacing, major tick spacing, display the ticks and the tick labels.

To get the selected value from JSlider we need to implements the stateChanged() method defined in the ChangeListener interface and then pass the listener to the JSlider by calling the addChangeListener() method.

package org.kodejava.example.swing;

import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;

public class JSliderDemo extends JPanel implements ChangeListener {
    private JTextField field;

    public JSliderDemo() {

    private void initializeUI() {
        setLayout(new BorderLayout());
        setPreferredSize(new Dimension(500, 200));

        // Creates an instance of JSlider with a horizontal
        // orientation. Define 0 as the minimal value and
        // 50 as the maximum value. The initial value is set
        // to 10.
        JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 50, 10);



        JLabel label = new JLabel("Selected Value:");
        field = new JTextField(5);

        JPanel panel = new JPanel();
        panel.setLayout(new FlowLayout());

        add(slider, BorderLayout.NORTH);
        add(panel, BorderLayout.SOUTH);

    public void stateChanged(ChangeEvent e) {
        JSlider slider = (JSlider) e.getSource();

        // Get the selection value of JSlider

    public static void showFrame() {
        JPanel panel = new JSliderDemo();

        JFrame frame = new JFrame();
        frame.setTitle("JSlider Demo");

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {

Below is the result of the code snippet above.

JSlider Demo

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. You can support my works by donating here. Thank you 🥳

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.