How do I create a JSlider with custom labels?

The JSlider‘s setLabelTable() method allows you to define a custom labels for the JSlider. The label table is a Hashtable that contains an Integer number as the keys and a JLabel component as their values. The integer keys correspond to the JSlider tick where the labels will be customized.

package org.kodejava.example.swing;

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

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

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

        JSlider slider = new JSlider(JSlider.VERTICAL, 0, 40, 0);
        slider.setMinorTickSpacing(1);
        slider.setMajorTickSpacing(5);
        slider.setPaintTicks(true);

        Hashtable<Integer, JLabel> labels = new Hashtable<>();
        labels.put(0, new JLabel("Freezing"));
        labels.put(15, new JLabel("Cold"));
        labels.put(25, new JLabel("Warm"));
        labels.put(35, new JLabel("Hot"));
        slider.setLabelTable(labels);

        slider.setPaintLabels(true);

        add(slider, BorderLayout.CENTER);
    }

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

        JFrame frame = new JFrame("JSlider Custom Label");
        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() {
                JSliderCustomLabel.showFrame();
            }
        });
    }
}

The screen capture of the example above is:

JSlider with Custom Labels 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.