Java JSlider

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

Java JSlider

The Java JSlider class is used to create the slider. By using JSlider, a user can select a value from a specific range.

Commonly used Constructors of JSlider class

Constructor

Description

JSlider()

creates a slider with the initial value of 50 and range of 0 to 100.

JSlider(int orientation)

creates a slider with the specified orientation set by either JSlider.HORIZONTAL or JSlider.VERTICAL with the range 0 to 100 and initial value 50.

JSlider(int min, int max)

creates a horizontal slider using the given min and max.

JSlider(int min, int max, int value)

creates a horizontal slider using the given min, max and value.

JSlider(int orientation, int min, int max, int value)

creates a slider using the given orientation, min, max and value.

 

Commonly used Methods of JSlider class

Method

Description

public void setMinorTickSpacing(int n)

is used to set the minor tick spacing to the slider.

public void setMajorTickSpacing(int n)

is used to set the major tick spacing to the slider.

public void setPaintTicks(boolean b)

is used to determine whether tick marks are painted.

public void setPaintLabels(boolean b)

is used to determine whether labels are painted.

public void setPaintTracks(boolean b)

is used to determine whether track is painted.

Java JSlider Example

  1. import javax.swing.*;  
  2. public class SliderExample1 extends JFrame{  
  3. public SliderExample1() {  
  4. JSlider slider = new JSlider(JSlider.HORIZONTAL, 05025);  
  5. JPanel panel=new JPanel();  
  6. panel.add(slider);  
  7. add(panel);  
  8. }  
  9.   
  10. public static void main(String s[]) {  
  11. SliderExample1 frame=new SliderExample1();  
  12. frame.pack();  
  13. frame.setVisible(true);  
  14. }  
  15. }  

Output:

example of JSlider class

Java JSlider Example: painting ticks

  1. import javax.swing.*;  
  2. public class SliderExample extends JFrame{  
  3. public SliderExample() {  
  4. JSlider slider = new JSlider(JSlider.HORIZONTAL, 05025);  
  5. slider.setMinorTickSpacing(2);  
  6. slider.setMajorTickSpacing(10);  
  7. slider.setPaintTicks(true);  
  8. slider.setPaintLabels(true);  
  9.   
  10. JPanel panel=new JPanel();  
  11. panel.add(slider);  
  12. add(panel);  
  13. }  
  14. public static void main(String s[]) {  
  15. SliderExample frame=new SliderExample();  
  16. frame.pack();  
  17. frame.setVisible(true);  
  18. }  
  19. }  

Output:

example of JSlider class