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

How to Use Scroll Panes

The 1.1 AWT introduced the ScrollPane(in the API reference documentation) class, which makes it easy for you to provide a scrolling area. A ScrollPane manages a single child component, displaying as much of the component as space permits.

By default, a scroll pane's scrollbars are visible only when they're needed. For example, if a scroll pane is wide enough to show its child's full width, then the horizontal scrollbar isn't needed, and by default the horizontal scrollbar will completely disappear. The following picture shows an applet in which both the vertical and horizontal scrollbars are currently needed.

Here is the code that creates a scroll pane and puts a child component in it:

ScrollPane sp1 = new ScrollPane();
When you create a scroll pane (but not later), you can specify when the scroll pane shows scrollbars, using one of these three ScrollPane constants:

The default value. Show each scrollbar only when it's needed.
Always show scrollbars.
Never show scrollbars. You might use this option if you don't want the user to directly control what part of the child component is shown.

Here's an example of specifying the scrollbar display policy:

ScrollPane sp2 = new ScrollPane(ScrollPane.SCROLLBARS_ALWAYS);

When you implement a component to be put in a scroll pane, you must take special care:

Here's the scrolling-related code from the previous applet:

//The component that will be scrolled.
class ScrollableCanvas extends Canvas {
    Dimension preferredSize = new Dimension(600, 320);
    Dimension minimumSize = new Dimension(10, 10);

    public Dimension getMinimumSize() {
        return minimumSize;

    public Dimension getPreferredSize() {
        return preferredSize;

    public void paint(Graphics g) {
        g.drawImage(image, 0, 0, getBackground(), this);

public class ImageScroller ... {
    ...//where initialization occurs:
        ScrollableCanvas canvas = new ScrollableCanvas();
        ScrollPane pane = new ScrollPane();
        setLayout(new BorderLayout());
        add("Center", pane);

Scroll panes don't generate events. If you want to be notified of scrolling activity, then you can get the scroll pane's scrollbars and listen to adjustment events from them. The horizontal scrollbar is returned by the ScrollPane getHAdjustable method, and the vertical scrollbar by the getVAdjustable method.

Another reason you might need to get the scrollbars is to control the scrollbars' appearance or behavior. For example, in a text processor you might need to set the amount scrolled when the user clicks in the scrollbar. For information on setting scrollbar attributes, see How to Use Scrollbars.

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