Java Swing How to - Show Tick Marks Within a JSlider








Question

We would like to know how to show Tick Marks Within a JSlider.

Answer

/* ww w. ja  v a2  s. co  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 TickSliders {
  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);
  }
}