How do I reverse JSlider’s value-range?

On a normal JSlider the value range displayed left-to-right on a horizontal JSlider and bottom-to-top on vertical JSlider. To reverse the slider values from their normal order you can use the setInverted() method of the JSlider instance. Passing a true boolean value into this method call reverse the values order.

package org.kodejava.example.swing;

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

public class JSliderInvertedDemo extends JPanel {
    public JSliderInvertedDemo() {
        initializeUI();
    }

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

        JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 20, 10);
        slider.setMinorTickSpacing(1);
        slider.setMajorTickSpacing(5);
        slider.setPaintLabels(true);
        slider.setPaintTicks(true);

        // Reverse the value-range of a JSlider. On a normal
        // horizontal JSlider the maximum value is on the right
        // side. Specifying inverted to true makes the maximum
        // value placed on the left side.
        slider.setInverted(true);

        add(slider, BorderLayout.CENTER);
    }

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

        JFrame frame = new JFrame("Inverted JSlider");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setContentPane(panel);
        frame.pack();
        frame.setVisible(true);
    }

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

The result of the code snippet above is:

Inverted 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.