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



In this article, we will learn how to set major tick marks in a JSlider component in Java. A JSlider is a Swing component that allows users to select a numeric value from a range. Tick marks help improve user experience by marking specific intervals along the slider. Major tick marks represent larger intervals, and we can control their spacing using the setMajorTickSpacing() method.

Problem Statement

Given a slider with a range of values, write a Java program to set major tick marks every 25 units in a JSlider and display the slider in a GUI window.
Input
A slider with a range of values from 0 to 100.
Major tick marks spaced at 25 units.
Output
A graphical user interface (GUI) displaying a JSlider with major tick marks at intervals of 25 units: 0, 25, 50, 75, 100.

Steps to set major tick marks in a JSlider

The following are the steps to set major tick marks in a JSlider

  • Import the necessary Swing components from javax.swing.
  • Create a JFrame to hold the slider.
  • Create a JSlider with the desired range (0 to 100).
  • Set the major tick spacing to 25 units using the setMajorTickSpacing() method.
  • Ensure tick marks are painted by setting setPaintTicks(true).
  • Add the slider to a JPanel and add the panel to the frame.
  • Set the frame's properties (size, close operation, and visibility).

Java program to set major tick marks in a JSlider

The following is a program to set major tick marks in a JSlider

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

Code Explanation

A JSlider is created with a horizontal orientation, a range of 0 to 100, and an initial value of 55. The setMajorTickSpacing() method sets major ticks at 25-unit intervals, and setMinorTickSpacing() sets minor ticks at 10-unit intervals. By enabling setPaintTicks(true) and setPaintLabels(true), labels are shown. The slider is added to a panel, which is then added to the JFrame.

Updated on: 2024-11-07T01:05:52+05:30

351 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements