How do I create a JSlider that snap to the closest tick mark?

The JSlider‘s setSnapToTicks() method call is used to move JSlider‘s knob to the nearest tick mark from where you positioned the knob. The default value of this property is false. To make it snap to the closest tick set this property to true.

package org.kodejava.example.swing;

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

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

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

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

        // Snaps to the closest tick mark next to where the user
        // positioned the knob.
        slider.setSnapToTicks(true);

        add(slider, BorderLayout.CENTER);
    }

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

        JFrame frame = new JFrame("JSlider - Snap to Tick");
        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() {
                SnapToTickJSlider.showFrame();
            }
        });
    }
}

The screen capture of the result of the code snippet above is:

JSlider Snap to Ticks 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.