How to create Horizontal Slider in Java?

Java 8Object Oriented ProgrammingProgramming

To create Horizontal slider in Java, use the Swing JSlider. Let us first create a frame and a Horizontal slider in it −

JFrame frame = new JFrame("Frame with Slider");
JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 100, 70);

Now, we will set the values for the slider. Display the ticks −

slider.setMinorTickSpacing(5);
slider.setMajorTickSpacing(20);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
Add the slider in the panel:
JPanel panel = new JPanel();
panel.add(slider);

The following is an example to create horizontal slider −

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, 70);
      slider.setMinorTickSpacing(5);
      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(500, 300);
      frame.setVisible(true);
   }
}

Output


raja
Published on 04-Jun-2019 11:43:46
Advertisements