How to Use the JScrollPane Class to Create Text Areas with Scroll Bars in Java

By Doug Lowe

Text areas aren’t very useful without scroll bars. To create a text area with a scroll bar in Java, you use the JScrollPane class, whose constructors and fields are listed.

Note: This table doesn’t show any methods for the JScrollPane class. The JScrollPane class does have methods (plenty of them, in fact), but none of them are particularly useful for ordinary programming, so you won’t find them here.

Constructor Description
JScrollPane(Component view) Creates a scroll pane for the specified component.
JScrollPane(Component, int vert, int
hor)
Creates a scroll pane for the specified component with the
specified policy for the vertical and horizontal scroll bars.
Field
VERTICAL_SCROLLBAR_ALWAYS Always adds a vertical scroll bar.
VERTICAL_SCROLLBAR_AS_NEEDED Adds a vertical scroll bar if necessary.
VERTICAL_SCROLLBAR_NEVER Never adds a vertical scroll bar.
HORIZONTAL_SCROLLBAR_ALWAYS Always adds a horizontal scroll bar.
HORIZONTAL_SCROLLBAR_AS_NEEDED Adds a horizontal scroll bar if necessary.
HORIZONTAL_SCROLLBAR_NEVER Never adds a horizontal scroll bar.

The usual way to create a scroll pane is to use the second constructor. You use the first parameter of this constructor to specify the component to which you want to add scroll bars. To add scroll bars to a textNovel text area, for example, you specify textNovel as the first parameter.

The second parameter tells the scroll pane whether to create a vertical scroll bar. The value you specify for this parameter should be one of the first three fields listed:

  • VERTICAL_SCROLLBAR_ALWAYS: Choose this field if you always want the scroll pane to show a vertical scroll bar.

  • VERTICAL_SCROLLBAR_AS_NEEDED: Specify this field if you want to see the vertical scroll bar only when the text area contains more lines that can be displayed at once; the vertical scroll bar is shown only when it’s needed.

  • VERTICAL_SCROLLBAR_NEVER: Choose this field if you never want to see a vertical scroll bar onscreen.

The third parameter uses the three HORIZONTAL_SCROLLBAR constants to indicate whether the scroll pane includes a horizontal scroll bar always, never, or only when necessary.

Thus the following code adds scroll bars to a text area. The vertical scroll bar is always shown, but the horizontal scroll bar is shown only when needed:

JScrollPane scroll = new JScrollPane(textNovel,
 JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
 JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

Use the JScrollPane class with components other than text areas. Scroll panes are often used with list controls as well.