Header javaperspective.com
JavaPerspective.com  >   Intermediate Tutorials  >   5. Graphical User Interfaces  >   5.8. Scroll panes

5.8. Scroll panes
Last updated: 25 January 2013.

This tutorial will show you how to use scroll panes in Java.

When a component or its content is larger than its display area, you can wrap a scroll pane around that component. A scroll pane can have a vertical scroll bar only, a horizontal scroll bar only or both scroll bars. The following picture shows a frame containing a scroll pane (with both scroll bars) that is wrapped around a text area:

Scroll pane

A scroll pane is an instance of the class JScrollPane. Here is the code that builds the frame shown above:

import java.awt.Dimension;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

public final class ScrollPanes extends JFrame {

public ScrollPanes() {


private void addComponents() {
// Create the content pane
JPanel contentPane = new JPanel();

// Create the text area
JTextArea textArea = new JTextArea();

// Create the scroll pane and wrap it around the text area
JScrollPane scrollPane = new JScrollPane(textArea);
(new Dimension(350, 150));

// Add the scroll pane to the content pane

// Add the content pane to the JFrame

private void init() {
catch(Exception e){

(400, 200);

public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ScrollPanes();

As you can see, the code is quite simple. The constructor of the class JScrollPane that I have used does not specify the scroll bar policy to set. Therefore, it is the default policy that is set: the scroll bars appear only when needed.

You can specify a different scroll bar policy by calling the constructor JScrollPane(Component view, int vsbPolicy, int hsbPolicy). The argument vsbPolicy is the vertical scroll bar policy and hsbPolicy is the horizontal scroll bar policy. The possible values for vsbPolicy are JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED and JScrollPane.VERTICAL_SCROLLBAR_NEVER.

Of course, these constants have horizontal counterparts you can choose from to specify the value of hsbPolicy which sets the horizontal scroll bar policy. The constants are: JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED and JScrollPane.HORIZONTAL_SCROLLBAR_NEVER.

You are here :  JavaPerspective.com  >   Intermediate Tutorials  >   5. Graphical User Interfaces  >   5.8. Scroll panes
Next tutorial :  JavaPerspective.com  >   Intermediate Tutorials  >   5. Graphical User Interfaces  >   5.9. Labels

Copyright © 2013 - 2016. JavaPerspective.com. All rights reserved.  ( Terms | Contact | About ) 
Java is a trademark of Oracle Corporation
Image 1 Image 2 Image 3 Image 4 Image 5 Image 6 Image 7