Java Swing How to - Snap the JSlider Thumb into Position








Question

We would like to know how to snap the JSlider Thumb into Position.

Answer

//from  w w w .  ja  va  2 s .  c  o  m
import java.awt.BorderLayout;

import javax.swing.BoundedRangeModel;
import javax.swing.JFrame;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class Main {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Tick Slider");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JSlider jSliderOne = new JSlider();

    // Major Tick 25 - Minor 5
    jSliderOne.setMinorTickSpacing(5);
    jSliderOne.setMajorTickSpacing(25);
    jSliderOne.setPaintTicks(true);
    jSliderOne.setSnapToTicks(true);

    frame.add(jSliderOne, BorderLayout.NORTH);
    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}