Java JScrollBar

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

Java JScrollBar

The object of JScrollbar class is used to add horizontal and vertical scrollbar. It is an implementation of a scrollbar. It inherits JComponent class.

JScrollBar class declaration

Let's see the declaration for javax.swing.JScrollBar class.

  1. public class JScrollBar extends JComponent implements Adjustable, Accessible  

Commonly used Constructors:

Constructor

Description

JScrollBar()

Creates a vertical scrollbar with the initial values.

JScrollBar(int orientation)

Creates a scrollbar with the specified orientation and the initial values.

JScrollBar(int orientation, int value, int extent, int min, int max)

Creates a scrollbar with the specified orientation, value, extent, minimum, and maximum.

Java JScrollBar Example

  1. import javax.swing.*;  
  2. class ScrollBarExample  
  3. {  
  4. ScrollBarExample(){  
  5.     JFrame f= new JFrame("Scrollbar Example");  
  6.  JScrollBar s=new JScrollBar();  
  7. s.setBounds(100,10050,100);  
  8. f.add(s);  
  9. f.setSize(400,400);  
  10. f.setLayout(null);  
  11. f.setVisible(true);  
  12. }  
  13. public static void main(String args[])  
  14. {  
  15. new ScrollBarExample();  
  16. }}  

Java JScrollBar Example with AdjustmentListener

  1. import javax.swing.*;  
  2. import java.awt.event.*;  
  3. class ScrollBarExample  
  4. {  
  5. ScrollBarExample(){  
  6.     JFrame f= new JFrame("Scrollbar Example");  
  7.     final JLabel label = new JLabel();          
  8.     label.setHorizontalAlignment(JLabel.CENTER);    
  9.     label.setSize(400,100);  
  10.     final JScrollBar s=new JScrollBar();  
  11.     s.setBounds(100,10050,100);  
  12.     f.add(s); f.add(label);  
  13.     f.setSize(400,400);  
  14.    f.setLayout(null);  
  15.    f.setVisible(true);  
  16.    s.addAdjustmentListener(new AdjustmentListener() {  
  17.     public void adjustmentValueChanged(AdjustmentEvent e) {  
  18.        label.setText("Vertical Scrollbar value is:"+ s.getValue());  
  19.     }  
  20.  });  
  21. }  
  22. public static void main(String args[])  
  23. {  
  24.    new ScrollBarExample();  
  25. }}