How to change the maximum value of a JSlider in Java?

Java 8Object Oriented ProgrammingProgramming

To change the maximum value of a slider in Java, use the setMaximum() method wherein set the maximum value.

Let’s say the following is our slider in Java −

JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 100, 55);
slider.setMinorTickSpacing(10);
slider.setMajorTickSpacing(25);
slider.setPaintTicks(true);
slider.setPaintLabels(true);

Now, set the maximum value −

slider.setMaximum(150);

The following is an example to change the maximum value of a slidier −

Example

package my;
import java.awt.Color;
import java.awt.Font;
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.setMinorTickSpacing(10);
      slider.setMajorTickSpacing(25);
      slider.setPaintTicks(true);
      slider.setPaintLabels(true);
      slider.setBackground(Color.CYAN);
      slider.setForeground(Color.black);
      slider.setMaximum(150);
      Font font = new Font("Serif", Font.BOLD, 13);
      slider.setFont(font);
      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 07:43:57
Advertisements