How to Use Scroll Panes

How to Use Scroll Panes

A JScrollPane[121] provides a scrollable view of a component. When screen real estate is limited, use a scroll pane to display a component that is large or one whose size can change dynamically. (See Figure.) Other containers used to save screen space include split panes and tabbed panes.

[121] JScrollPane API documentation:

A screenshot of a demo program that puts a text area in a scroll pane because the text area's size grows dynamically as text is appended to it.


The code to create a scroll pane can be minimal. For example, here's the code from ToolBarDemo that creates the text area, makes it the scroll pane's client, and adds the scroll pane to a container:

//In a container that uses a BorderLayout:

textArea = new JTextArea(5, 30);


JScrollPane scrollPane = new JScrollPane(textArea);


setPreferredSize(new Dimension(450, 110));


add(scrollPane, BorderLayout.CENTER);

The boldface line of code creates the JScrollPane, specifying the text area as the scroll pane's client. The program doesn't invoke any methods on the JScrollPane object, since the scroll pane handles everything automatically: creating the scroll bars when necessary, redrawing the client when the user moves the scroll knobs, and so on.

You might have noticed that the preceding code sets the preferred size of the scroll pane's container. In the Java look and feel, this preferred size happens to be a bit less tall than required for the text area to display the 5 rows that we requested when creating it, so the scroll bar initially displays a vertical scroll bar. If we didn't restrict the size of the scroll pane's container, the scroll pane would be big enough for the text area to display the full 5 rows and 30 columns specified with the JTextArea constructor. Refer to Sizing a Scroll Pane (page 336) for information about techniques for making a scroll pane the size you want.

How a Scroll Pane Works

Figure is a snapshot of an application that uses a customized scroll pane to view a large photograph.

Figure. A screenshot of the ScrollDemo example, which uses scroll panes.


The scroll pane in this application looks very different from the one in the previous demo program. Rather than displaying text, this scroll pane contains a large image. The scroll pane also has two scroll bars, a row header, a column header, and four corners, three of which have been customized.

Try This:

  1. graphics/cd_icon.gif

    Run ScrollDemo using Java Web Start or compile and run the example yourself.[122]

    [122] To run ScrollDemo using Java Web Start, click the ScrollDemo link on the RunExamples/components.html page on the CD. You can find the source files here: JavaTutorial/uiswing/components/example-1dot4/index.html#ScrollDemo.

  2. Move the knobs on the scroll bars. Watch the image scroll and the horizontal and vertical rulers scroll along.

  3. If you have a mouse with a wheel (which is generally between the mouse buttons) use the mouse wheel to scroll the image vertically. Support for mouse-wheel scrolling was added in 1.4.

  4. Click the cm toggle in the upper left corner of the scroll pane. The units on the row and column headers change to inches (or back to centimeters).

  5. Click the arrow buttons on the scroll bars. Also, try clicking on the track above or below the knob on the vertical scroll bar or to the left or right of the horizontal one.

  6. Move the cursor over the image and press the cursor. Continuing to press the cursor, drag to a point outside the image and pause. The visible area of the image moves toward the cursor. This scroll-by-dragging functionality is enabled by the scroll pane and by the JComponent API, but implemented by the custom component that displays the image.

  7. Resize the window. Notice that the scroll bars disappear when the scroll pane is large enough to display the entire image and reappear when the scroll pane is too small to show the entire image.

The ScrollDemo program establishes the scroll pane's client when creating the scroll pane:

//Where the member variables are declared:

private ScrollablePicture picture;


//Where the GUI is created:

picture = new ScrollablePicture( ... );

JScrollPane pictureScrollPane = new JScrollPane(picture);

The scroll pane's client is also known as the view or viewport view. You can change the client dynamically by calling the setViewportView method. Note that JScrollPane has no corresponding getViewportView method. If you need to refer to the client object again, you can either cache it in a variable or invoke getViewport().getViewportView() on the scroll pane. (See Figure.)

This figure shows the relationship between the scroll pane and its client and indicates the classes that the scroll pane commissions to help.


When the user manipulates the scroll bars in a scroll pane, the area of the client that is visible changes accordingly.

A scroll pane uses a JViewport[123] instance to manage the visible area of the client. The viewport is responsible for computing the bounds of the current visible area, based on the positions of the scroll bars, and displaying it.

[123] JViewport API documentation:

A scroll pane uses two separate instances of JScrollBar[124] for the scroll bars. The scroll bars provide the interface for the user to manipulate the visible area.

[124] JScrollBar API documentation:

Figure shows the three areas of a scroll bar.

Figure. Scrollbar areas: the knob (sometimes called the thumb), the buttons, and the track.


When the user moves the knob on the vertical scroll bar up and down, the visible area of the client moves up and down. (See Figure.) Similarly, when the user moves the knob on the horizontal scroll bar to the right and left, the visible area of the client moves back and forth accordingly. The position of the knob relative to its track is proportionally equal to the position of the visible area relative to the client. In the Java look and feel and some others, the size of the knob gives a visual clue as to how much of the client is visible.

By clicking a button, the user can scroll by a unit increment. By clicking within the track, the user can scroll by a block increment. If the user has a mouse with a wheel, then the user can scroll vertically using the mouse wheel. The amount that the mouse wheel scrolls is platform dependent. For example, by default on Windows XP, the mouse wheel scrolls three unit increments; the Mouse control panel allows you to specify a different number of unit increments or to use a block increment instead. More information about unit and block increments is in Implementing a Scrolling-Savvy Client (page 333).

Typical programs don't directly instantiate or call methods on a viewport or scroll bar. Instead, programs achieve their scrolling behavior using the JScrollPane API and the API discussed in Implementing a Scrolling-Savvy Client (page 333). Some scrolling-savvy components such as JList, JTable, and JTree also provide additional API to help you affect their scrolling behavior.

Setting the Scroll Bar Policy

On startup, the scroll pane in the ScrollDemo application has two scroll bars. If you make the window very large, both scroll bars disappear because they are no longer needed. If you then shrink the height of the window without changing its width, the vertical scroll bar reappears. Further experimentation will show that in this application both scroll bars disappear and reappear as needed. This behavior is controlled by the scroll pane's scroll bar policy. Actually, it's two policies: Each scroll bar has its own.

ScrollDemo doesn't explicitly set the scroll pane's scroll bar policies—it uses the default. You can set the policies when you create the scroll pane or change them dynamically.

Of the constructors provided by JScrollPane, these two let you set the scroll bar policies when you create the scroll pane:

JScrollPane(Component, int, int)

JScrollPane(int, int)

The first int specifies the policy for the vertical scroll bar; the second specifies the policy for the horizontal scroll bar. You can also set the policies dynamically with the setHorizontalScrollBarPolicy and setVerticalScrollBarPolicy methods. With both the constructors and the methods, use one of the following constants defined in the ScrollPane-Constants[125] interface (which is implemented by JScrollPane):

[125] ScrollPaneConstants API documentation:





The default. The scroll bar appears when the viewport is smaller than the client and disappears when the viewport is larger than the client.



Always display the scroll bar. The knob disappears if the viewport is large enough to show the whole client.



Never display the scroll bar. Use this option if you don't want the user to directly control what part of the client is shown, or if you want them to use only non-scroll-bar techniques (such as dragging).

Providing Custom Decorations

The area drawn by a scroll pane consists of up to nine parts: the center, four sides, and four corners. The center is the only component that is always present in all scroll panes. Besides scroll bars, the sides can contain column and row headers. A corner component is visible only if both sides that intersect at that corner contain visible components.

As shown in Figure, the scroll pane in ScrollDemo has custom row and column headers. Additionally, because all four sides are populated, all four corners are present. The program customizes three of the corners—two just fill their area with the same color as the Rules, and the other contains a toggle button. The fourth corner, the lower right corner, is the default provided by the scroll pane. Notice that because the row and column headers are always present in this example, the toggle button is also always present.

Figure. The custom row and column headers in ScrollDemo.


If a corner contains a control that the user needs access to all the time, make sure the sides that intersect at the corner are always present. For example, if this application placed the toggle in the lower right corner where the scroll bars intersect, then the toggle would disappear if the user resized the window and even one of the scroll bars disappeared.

The scroll pane's row and column headers are provided by a custom JComponent subclass, Rule, that draws a ruler in centimeters or inches. Here's the code that creates and sets the scroll pane's row and column headers:

//Where the member variables are defined:

private Rule columnView;

private Rule rowView;


//Where the GUI is initialized:

ImageIcon david = createImageIcon("images/youngdad.jpeg");


//Create the row and column headers.

columnView = new Rule(Rule.HORIZONTAL, true);

rowView = new Rule(Rule.VERTICAL, true);

if (david != null) {







You can use any component for a scroll pane's row and column headers. The scroll pane puts the row and column headers in JViewPorts of their own. Thus, when scrolling horizontally, the column header follows along, and when scrolling vertically, the row header follows along.

As a JComponent subclass, our custom Rule class puts its rendering code in its paintComponent method. The Rule rendering code takes care to draw only within the current clipping bounds to ensure speedy scrolling. Your custom row and column headers should do the same.

You can also use any component for the corners of a scroll pane. ScrollDemo illustrates this by putting a toggle button in the upper left corner and custom Corner objects in the upper right and lower left corners. Here's the code that creates the Corner objects and calls setCorner to place them:

//Create the corners.

JPanel buttonCorner = new JPanel(); //use FlowLayout

isMetric = new JToggleButton("cm", true);

isMetric.setFont(new Font("SansSerif", Font.PLAIN, 11));

isMetric.setMargin(new Insets(2,2,2,2));




//Set the corners.




                            new Corner());


                            new Corner());

Remember that the size of each corner is determined by the size of the sides intersecting there. For some components you must take care that the specific instance of the component fits in its corner. For example, the program sets the font and margins on the toggle button so that it fits within the space established by the headers. It's not an issue with the Corner class because that class colors its entire bounds, whatever they happen to be, with a solid color.

As you can see from the code, constants indicate the corner positions (see Figure).

This figure shows the constant for each corner position.


The constants are defined in the ScrollPaneConstants interface, which JScrollPane implements.

Implementing a Scrolling-Savvy Client

To customize the way that a client component interacts with its scroll pane, you can make the component implement the Scrollable[126] interface. By implementing Scrollable, a client can specify both the size of the viewport used to view it and the amount to scroll for clicks on the different controls on a scroll bar.

[126] Scrollable API documentation:

Note: If you can't or don't want to implement a scrollable client, you can specify the unit and block increments using the setUnitIncrement and setBlockIncrement methods of JScrollBar. For example, the following code sets the unit increment for vertical scrolling to 10 pixels:


Figure shows, again, the three control areas of a scroll bar: the knob, the buttons, and the track.

The control areas of a scroll bar.


You might have noticed when manipulating the scroll bars in ScrollDemo that clicking the buttons scrolls the image to a tick boundary. You might also have noticed that clicking in the track scrolls the picture by a "screenful." More generally, the button scrolls the visible area by a unit increment and the track scrolls the visible area by a block increment. The behavior you see in the example is not the scroll pane's default behavior, but is specified by the client in its implementation of the Scrollable interface.

The client for the ScrollDemo program is ScrollablePicture. ScrollablePicture is a subclass of JLabel that provides implementations of all five Scrollable methods:

  • getScrollableBlockIncrement

  • getScrollableUnitIncrement

  • getPreferredScrollableViewportSize

  • getScrollableTracksViewportHeight

  • getScrollableTracksViewportWidth

ScrollablePicture implements the Scrollable interface primarily to affect the unit and block increments. However, it must provide implementations for all five methods. Thus, it provides reasonable defaults for the other three methods that you might want to copy for your scrolling-savvy classes.

The scroll pane calls the client's getScrollableUnitIncrement method whenever the user clicks one of the buttons on the scroll bar. This method returns the number of pixels to scroll. An obvious implementation of this method returns the number of pixels between tick marks on the header rulers. ScrollablePicture, however, does something different: It returns the value required to position the image on a tick mark boundary. Here's the implementation:

public int getScrollableUnitIncrement(Rectangle visibleRect,

                                      int orientation,

                                      int direction) {

    //Get the current position.

    int currentPosition = 0;

    if (orientation == SwingConstants.HORIZONTAL) {

        currentPosition = visibleRect.x;

    } else {

        currentPosition = visibleRect.y;


    //Return the number of pixels between currentPosition

    //and the nearest tick mark in the indicated direction.

    if (direction < 0) {

        int newPosition = currentPosition -

                         (currentPosition / maxUnitIncrement)

                          * maxUnitIncrement;

        return (newPosition == 0) ? maxUnitIncrement : newPosition;

    } else {

        return ((currentPosition / maxUnitIncrement) + 1)

                 * maxUnitIncrement

                 - currentPosition;



If the image is already on a tick mark boundary, this method returns the number of pixels between ticks. Otherwise, it returns the number of pixels from the current location to the nearest tick.

Likewise, the scroll pane calls the client's getScrollableBlockIncrement method each time the user clicks on the track. Here's ScrollablePicture's implementation of this method:

public int getScrollableBlockIncrement(Rectangle visibleRect,

                                       int orientation,

                                       int direction) {

    if (orientation == SwingConstants.HORIZONTAL)

        return visibleRect.width - maxUnitIncrement;


        return visibleRect.height - maxUnitIncrement;


This method returns the height of the visible rectangle minus a tick mark. This behavior is typical. A block increment should be slightly smaller than the viewport to leave a little of the previous visible area for context. For example, a text area might leave one or two lines of text for context and a table might leave a row or column (depending on the scroll direction). has one more bit of code that's not required by the Scrollable interface but is common in scrollable components: a mouse-motion listener that lets the user scroll the picture by dragging from it. The boldface code in the following snippet implements scrolling by dragging:

public class ScrollablePicture extends JLabel

                               implements Scrollable,

                                          MouseMotionListener {


    public ScrollablePicture(...) {


        setAutoscrolls(true); //enable synthetic drag events

        addMouseMotionListener(this); //handle mouse drags



    public void mouseDragged(MouseEvent e) {

        //The user is dragging us, so scroll!

        Rectangle r = new Rectangle(e.getX(), e.getY(), 1, 1);





This snippet scrolls the picture whenever the user drags from the picture to a location outside the picture and pauses. The setAutoscrolls method is defined by JComponent for the purpose of assisting—but not implementing—scrolling by dragging. Setting the autoscrolls property to true makes the component fire synthetic mouse-dragged events even when the mouse isn't moving (because it stopped, mid-drag, outside the component). It's up to the component's mouse motion listener to listen for these events and react accordingly.

Sizing a Scroll Pane

Unless you explicitly set a scroll pane's preferred size, the scroll pane computes it based on the preferred size of its nine components (the viewport and, if present, the two scroll bars, the row and column headers, and the four corners). The largest factor, and the one most programmers care about, is the size of the viewport used to display the client.

If the client is not scrolling-savvy, then the scroll pane sizes itself so that the client displays at its preferred size. For typical unsavvy clients, this makes the scroll pane redundant. That is, the scroll pane has no scroll bars because the client's preferred size is big enough to display the entire client. In this case, if the client doesn't change size dynamically, you should probably limit the size of the scroll pane by setting its preferred size or the preferred size of its container.

If the client is scrolling-savvy, then the scroll pane uses the value returned by the client's getPreferredScrollableViewportSize method to compute the size of its viewport. Implementations of this method generally report a preferred size for scrolling that's smaller than the component's standard preferred size. For example, by default the value returned by JList's implementation of getPreferredScrollableViewportSize is just big enough to display eight rows.

Scrolling-savvy classes, like lists, tables, text components, and trees, often provide one or more methods that let programmers affect the size returned from getPreferredScroll-ableViewportSize. For example, you can set the number of visible rows in a list or a tree by calling the setVisibleRowCount method. The list or tree takes care of figuring out the size needed to display that number of rows.

Refer to Figure (page 340) for information about scrolling-related methods provided by classes other than JScrollPane. And remember—if you don't like the value that getPreferredScrollableViewportSize returns, you can always set the preferred size of the scroll pane or its container.

Dynamically Changing the Client's Size

Changing the size of a scroll pane's client is a two-step process. First set the client's preferred size. Then, call revalidate on the client to let the scroll pane know that it should update itself and its scroll bars. Let's look at an example.

Figure is a picture of an application that changes the client's size whenever the user places a circle whose bounds fall outside of the client's current bounds. The program also changes the client's size when the user clears the drawing area.

Figure. A screenshot of the ScrollDemo2 example.



You can run ScrollDemo2 using Java Web Start or compile and run the example yourself.[127]

[127] To run ScrollDemo2 using Java Web Start, click the ScrollDemo2 link on the RunExamples/components.html page on the CD. You can find the source files here: JavaTutorial/uiswing/components/example-1dot4/index.html#ScrollDemo2.

if (changed) {

    //Update client's preferred size because

    //the area taken up by the graphics has

    //gotten larger or smaller (if cleared).

    drawingArea.setPreferredSize(/* the new size */);

    //Let the scroll pane know to update itself

    //and its scroll bars.



When the client changes size, the scroll bars adjust. The scroll pane doesn't resize, nor does the viewport. Refer to SplitPaneDemo in How to Use Split Panes (page 369) for another example in which the client object changes size.

The Scroll Pane API

Figure through 70 list the commonly used scroll-related constructors and methods. Other methods you are most likely to invoke on a JScrollPane object are those such as setPreferredSize that its superclasses provide. See The JComponent API (page 55) for tables of commonly used inherited methods. See also the API documentation for JScrollPane, ScrollPaneConstants, and Scrollable:

Figure Setting up the Scroll Pane (JScrollPane constructors and methods)

Method or Constructor




JScrollPane(int, int)

JScrollPane(Component,int, int)

Create a scroll pane. The Component parameter, when present, sets the scroll pane's client. The two int parameters, when present, set the vertical and horizontal scroll bar policies (respectively).

void setViewportView(Component)

Set the scroll pane's client.

void setVerticalScrollBarPolicy(int)

int getVerticalScrollBarPolicy()

Set or get the vertical scroll policy. ScrollPane-Constants defines three values for specifying this policy: VERTICAL_SCROLLBAR_AS_NEEDED (the default), VERTICAL_SCROLLBAR_ALWAYS, and VERTICAL_SCROLLBAR_NEVER.

void setHorizontalScrollBarPolicy(int)

int getHorizontalScrollBarPolicy()

Set or get the horizontal scroll policy. ScrollPane-Constants defines three values for specifying this policy: HORIZONTAL_SCROLLBAR_AS_NEEDED (the default), HORIZONTAL_SCROLLBAR_ALWAYS, and HORIZONTAL_SCROLLBAR_NEVER.

void setViewportBorder(Border)

Border getViewportBorder()

Set or get the border around the viewport.

void setWheelScrollingEnabled(boolean)

boolean isWheelScrollingEnabled()

Set or get whether scrolling occurs in response to the mouse wheel. Mouse-wheel scrolling is enabled by default. Introduced in 1.4.

Figure Decorating the Scroll Pane (JScrollPane methods)



void setColumnHeaderView(Component)

void setRowHeaderView(Component)

Set the column or row header for the scroll pane.

void setCorner(String, Component)

Component getCorner(String)

Set or get the corner specified. The int parameter specifies which corner and must be one of the following constants defined in ScrollPaneConstants: UPPER_LEFT_CORNER, UPPER_RIGHT_CORNER, LOWER_LEFT_CORNER, LOWER_RIGHT_CORNER, LOWER_LEADING_CORNER, LOWER_TRAILING_CORNER, UPPER_LEADING_CORNER, and UPPER_TRAILING_CORNER. The last four constants (LEADING/TRAILING) were introduced in 1.3, but aren't usable as late as 1.4.2 due to bug #4467063. Track this bug online at:

Implementing a Scrolling-Savvy Client



int getScrollableUnitIncrement(

                 Rectangle, int, int)

int getScrollableBlockIncrement(

                 Rectangle, int, int)

(required by the Scrollable interface)

Get the unit or block increment in pixels. The Rectangle parameter is the bounds of the currently visible rectangle. The first int parameter is either SwingConstants.HORIZONTAL or SwingConstants.VERTICAL depending on what scroll bar the user clicked on. The second int parameter indicates which direction to scroll. A value less than 0 indicates up or left. A value greater than 0 indicates down or right.

Dimension getPreferredScrollableViewportSize()

(required by the Scrollable interface)

Get the preferred size of the viewport. This allows the client to influence the size of the viewport in which it is displayed. If the viewport size is unimportant, implement this method to return getPreferredSize.

boolean getScrollableTracksViewportWidth()

boolean getScrollableTracksViewportHeight()

(required by the Scrollable interface)

Get whether the scroll pane should force the client to be the same width or height as the viewport. A return value of true from either of these methods effectively disallows horizontal or vertical scrolling (respectively).

void setAutoscrolls(boolean)

(in JComponent)

Set whether synthetic mouse-dragged events should be generated when the user drags the mouse outside of the component and stops; these events are necessary for scrolling by dragging. By default, the value is false, but many scrollable components such as JTable and custom components set the value to true.

Methods in Other Classes Related to Scrolling



void scrollRectToVisible(Rectangle)

(in JComponent)

If the component is in a container that supports scrolling, such as a scroll pane, then calling this method scrolls the scroll pane such that the specified rectangle is visible.

void setVisibleRowCount(int)

int getVisibleRowCount()

(in JList)

Set or get how many rows of the list are visible. The getPreferredScrollableViewportSize method uses the visible row count to compute its return value.

void ensureIndexIsVisible(int)

(in JList)

Scroll so that the row at the specified index is visible. This method calls scrollRectToVisible and works only if the list is in a container, such as a scroll pane, that supports scrolling.

void setVisibleRowCount(int)

int getVisibleRowCount()

(in JTree)

Set or get how many rows of the tree are visible. The getPreferredScrollableViewportSize method uses the visible row count to compute its return value.

void scrollPathToVisible(TreePath)

void scrollRowToVisible(int)

(in JTree)

Scroll so that the specified tree path or row at the specified index is visible. These methods call scrollRectToVisible and work only if the tree is in a container, such as a scroll pane, that supports scrolling.

void setScrollsOnExpand(boolean)

boolean getScrollsOnExpand()

(in JTree)

Set or get whether scrolling occurs automatically when the user expands a node. True by default. This feature works only when the tree is in a container, such as a scroll pane, that supports scrolling.

void setPreferredScrollableViewportSize(


(in JTable)

Set the value to be returned by getPreferredScrollableViewportSize.

Examples That Use Scroll Panes

This table shows some examples that use JScrollPane and where those examples are described.


Where Described



This section, How to Use Tool Bars (page 427)

Shows a simple, yet typical, use of a scroll pane.


This section

Uses many of scroll pane's bells and whistles.


This section

Shows how to change the client's size.


How to Use Split Panes (page 369), How to Use Lists (page 267)

Puts a list and a label in a scroll pane. Also, shows how to handle the case when a scroll pane's client changes size.


How to Use Tables (page 388)

Puts a table in a scroll pane.


Using Text Components (page 60)

Puts a text area, an editor pane, and a text pane in scroll panes.


How to Use Trees (page 437)

Puts a tree in a scroll pane.

     Python   SQL   Java   php   Perl 
     game development   web development   internet   *nix   graphics   hardware 
     telecommunications   C++ 
     Flash   Active Directory   Windows