java.awt.Scrollbar

Lists, TextAreas, and ScrollPanes come with ready made scrollbars. However if you want to scroll any other object you'll have to use a java.awt.Scrollbar. Scrollbars have many uses. At their most basic they're used for moving the visible area. They can also be used to set a value between two numbers. Or they can be used to flip through a number of screens as in a database operation that looks at successive records.

There are three constructors:

public Scrollbar()
public Scrollbar(int orientation)
public Scrollbar(int orientation, int value, int visible, int min, int max)

The orientation argument is one of the mnemonic constants, Scrollbar.HORIZONTAL or Scrollbar.VERTICAL. As you expect this determines whether the Scrollbar is laid out from left to right or top to bottom.

A Scrollbar has an int value at all times. This value will be between the minimum and the maximum value set by the last two arguments to the constructor. When a Scrollbar is created, its value is given by the value argument. The default is 0.

Finally visible represents the size of the visible portion of the scrollable area in pixels. The Scrollbar uses this when moving up or down a page.

A Scrollbar fires an adjustment event when its value changes. You register an adjustment listener to catch this event. This class needs an adjustmentValueChanged() method with this signature:

public void adjustmentValueChanged(AdjustmentEvent e)

The following program is an applet that changes the number in a TextField between 1 and 100 based on the position of the thumb (the movable part of the Scrollbar). In a practical application the number would of course mean something.

Scrollbar widget

import java.applet.*;    
import java.awt.*;
import java.awt.event.*;

public class Scrollie extends Applet implements AdjustmentListener {

  private TextField t;
  private Scrollbar sb;

  public void init() {
    int initialValue = 1;
    sb = new  Scrollbar(Scrollbar.HORIZONTAL, initialValue, 100, 1, 100);
    sb.addAdjustmentListener(this);
    this.add(sb);
    this.t = new TextField(4);
    this.t.setText(String.valueOf(initialValue));    
    this.add(t);
  }
  
  public void adjustmentValueChanged(AdjustmentEvent e)
     
    int val = sb.getValue();
    this.t.setText(String.valueOf(val));
    
  }
  
}

Previous | Next | Top | Cafe au Lait

Copyright 1997, 2003 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified April 8, 2003