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.swing;

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

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

    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(JSliderInvertedDemo::showFrame);
    }

    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);
    }
}

The result of the code snippet above is:

Inverted JSlider Demo

Wayan

Leave a Reply

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