Previous | Next | Trail Map | Creating a User Interface | Using Components, the GUI Building Blocks


How to Use Scrollbars

Scrollbars have two uses:

Here's a 1.0 applet that uses scrollbars to help control the display of a large image (it might take a minute for the image to load):


Note: The rest of this section discusses the 1.0 API for scrollbars. If you're writing a 1.1 program with a scrolling area, please skip the rest of this page and go to How to Use Scroll Panes.

To create a scrollbar, you need to create an instance of the Scrollbar(in the API reference documentation) class. You must also initialize the following values, either by specifying them to a Scrollbar constructor(in the API reference documentation) or by calling the setValues() method before the scrollbar is visible.

int orientation
Indicates whether the scrollbar should be horizontal or vertical. Specified with either Scrollbar.HORIZONTAL or Scrollbar.VERTICAL.
int value
The initial value of the scrollbar. For scrollbars that control a scrollable area, this usually means the x value (for horizontal scrollbars) or y value (for vertical scrollbars) of the part of the area that's visible when the user first sees the scrollable area. For example, when the applet above starts up, both the horizontal and vertical scrollbars' values are 0, and the image portion that's displayed starts at (0,0).
int visible
The size in pixels of the visible portion of the scrollable area. This value, if set before the scrollbar is visible, determines how many pixels a click in the scrollbar (but not on the knob) causes the display area to shift. Setting this value after the scrollbar is visible has no effect. After the scrollbar is visible, you should use the setPageIncrement() method to get the same effect.
int minimum
The minimum value the scrollbar can have. For scrollbars controlling scrollable areas, this value is usually 0 (the left/upper part of the area).
int maximum
The maximum value the scrollbar can have. For scrollbars controlling scrollable areas, this value is usually: (total width/height, in pixels, of the component that's being partially displayed) - (currently visible width/height of the scrollable area).
Here's a figure that illustrates the meaning of the above values:

Here's the code for the above applet. The code defines two classes. The first is a simple Canvas subclass (ScrollableCanvas) that draws an image. The second is a Panel subclass (ImageScroller, which actually extends Applet) that creates and contains a ScrollableCanvas and two Scrollbars. This program illustrates a few important details of managing a scrollable area:


Previous | Next | Trail Map | Creating a User Interface | Using Components, the GUI Building Blocks