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

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

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

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

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

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

JSlider Snap to Ticks Demo

Wayan

Leave a Reply

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