«Back to Home

Core Java

Topics

JSlider Class In Java

JSlider Class
 
In Java, JSlider creates the slider. Using JSlider, a user can select a value from a particular range.
 
Constructors of JSlider class

JSlider()
 
This constructor creates a slider with the initial value of 50 and the range of 0 to 100.
 
JSlider(int orientation)
 
This constructor creates a slider with the specific orientation, set by either JSlider.HORIZONTAL or JSlider.VERTICAL with the range 0 to 100 and initial value 50.
 
JSlider(int min, int max)
 
This constructor creates a horizontal slider, using the given min and max.
 
JSlider(int min, int max, int value)
 
This constructor creates a horizontal slider, using the given min, max and value.
 
JSlider(int orientation, int min, int max, int value)
 
This constructor creates a slider, using the given orientation, min, max and value.
 
Methods of JSlider class
 
public void setMinorTickSpacing(int n)
 
This method is used to set the minor tick spacing to the slider.
 
public void setMajorTickSpacing(int n)
 
This method is used to set the major tick spacing to the slider.
 
public void setPaintTicks(boolean b)
 
This method is used to determine whether tick marks are painted.
 
public void setPaintLabels(boolean b)
 
This method is used to determine whether labels are painted.
 
public void setPaintTracks(boolean b)
 
This method is used to determine whether track is painted.
 
Let’s see an example of JSlider class, given below.
 
Code
  1. import javax.swing.*;  
  2. public class JSliderExample extends JFrame {  
  3.     public JSliderExample() {  
  4.         JSlider js = new JSlider(JSlider.HORIZONTAL, 06035);  
  5.         JPanel jp = new JPanel();  
  6.         jp.add(js);  
  7.         add(jp);  
  8.     }  
  9.     public static void main(String s[]) {  
  10.         JSliderExample jse = new JSliderExample();  
  11.         jse.pack();  
  12.         jse.setVisible(true);  
  13.     }  
  14. }  
49

Output

50

Let’s see another example of jSlider class, given below.
 
Code
  1. import javax.swing.*;  
  2. public class JSliderExample extends JFrame {  
  3.     public JSliderExample() {  
  4.         JSlider js = new JSlider(JSlider.HORIZONTAL, 07045);  
  5.         js.setMinorTickSpacing(2);  
  6.         js.setMajorTickSpacing(10);  
  7.         js.setPaintTicks(true);  
  8.         js.setPaintLabels(true);  
  9.         JPanel jp = new JPanel();  
  10.         jp.add(js);  
  11.         add(jp);  
  12.     }  
  13.     public static void main(String s[]) {  
  14.         JSliderExample jse = new JSliderExample();  
  15.         jse.pack();  
  16.         jse.setVisible(true);  
  17.     }  
  18. }  
51

Output

52

Summary

Thus, we learnt that the JSlider creates the slider and using JSlider, a user can select a value from a particular range and also learnt how to use it in Java.