Java Program to set minor tick marks in a JSlider every 10 units

Java 8Object Oriented ProgrammingProgramming

Minor Tick marks is the number passed in representing the distance between each minor tick mark. For example, a slider with range from 0 to 70 and minor tick spacing 10, would give minor ticks next to the following values: 0, 10, 20, 30, 40, 50, 60, 70.

To set minor tick marks, use the setMinorTickSpacing() method −

JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 100, 60);
slider.setMinorTickSpacing(10);

Note − For minor ticks to be painted, you need to set setPaintTicks to true.

The following is an example to set minor tick marks in a slider every 10 units −

Example

package my;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.WindowConstants;
public class SwingDemo {
   public static void main(String[] args) {
      JFrame frame = new JFrame("Frame with Slider");
      JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 100, 60);
      slider.setInverted(false);
      slider.setMinorTickSpacing(10);
      slider.setMajorTickSpacing(20);
      slider.setPaintTicks(true);
      slider.setPaintLabels(true);
      JPanel panel = new JPanel();
      panel.add(slider);
      frame.add(panel);
      frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
      frame.setSize(600, 300);
      frame.setVisible(true);
   }
}

Output

raja
Published on 30-May-2019 12:00:00
Advertisements