Java Program to set major tick marks in a JSlider every 25 units

Java 8Object Oriented ProgrammingProgramming

Major Tick marks is the number passed in representing the distance between each major tick mark. 

For example, a slider with range from 0 to 75 and major tick spacing 25, would give major ticks next to the following values: 0, 25, 50, 75.

To set major tick marks, use the setMajorTickSpacing() method −

JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 100, 55);
slider.setMajorTickSpacing(25);

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

The following is an example to set major tick marks in a slider every 25 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, 55);
      slider.setInverted(false);
      slider.setMinorTickSpacing(10);
      slider.setMajorTickSpacing(25);
      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 04-Jun-2019 08:43:32
Advertisements