The JScrollBar Class

To program with a scrollbar, it is important to understand its anatomy. Scrollbars are composed of a rectangular tab, called a slider or thumb, located between two arrow buttons. The arrow buttons on either end increment or decrement the slider’s position by an adjustable number of units, generally one. In addition, clicking in the area between the thumb and the end buttons (often called the paging area) moves the slider one block, or 10 units by default. The user can modify the value of the scrollbar in one of three ways: by dragging the thumb in either direction, by pushing on either of the arrow buttons, or by clicking in the paging area.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ScrollBarExample extends JPanel {

    JLabel label;

    public ScrollBarExample( ) {
        label=new JLabel( );
        setLayout(new BorderLayout( ));

        JScrollBar hbar=new JScrollBar(JScrollBar.HORIZONTAL, 30, 20, 0, 300);
        JScrollBar vbar=new JScrollBar(JScrollBar.VERTICAL, 30, 40, 0, 300);


        hbar.addAdjustmentListener(new MyAdjustmentListener( ));
        vbar.addAdjustmentListener(new MyAdjustmentListener( ));

        add(hbar, BorderLayout.SOUTH);
        add(vbar, BorderLayout.EAST);
        add(label, BorderLayout.CENTER);

    class MyAdjustmentListener implements AdjustmentListener {
        public void adjustmentValueChanged(AdjustmentEvent e) {
           label.setText("    New Value is " + e.getValue( ) + "      ");
           repaint( );

    public static void main(String s[]) {
         JFrame frame = new JFrame("Scroll Bar Example");
         frame.setContentPane(new ScrollBarExample( ));