Java JScrollPane

JScrollPane is a lightweight container that automatically handles the scrolling of another component. The component being scrolled can either be an individual component. If the object being scrolled is larger than the viewable area, horizontal and/or vertical scroll bars are automatically provided, and the component can be scrolled through the pane. Because JScrollPane automates scrolling, it usually eliminates the need to manage individual scroll bars.

The viewable area of a scroll pane is called the viewport. It is a window in which the component being scrolled is displayed. Thus, the viewport displays the visible portion of the component being scrolled. The scroll bars scroll the component through the viewport. In its default behaviour, a JScrollPane will dynamically add or remove a scroll bar as needed.

Example:
If the component is taller than the viewport, a vertical scroll bar is added. If the component will completely fit within the viewport, the scroll bars are removed. JScrollPane defines several constructors.

JScrollPane(Component comp)

The component to be scrolled is specified by comp.

General Procedure to use ScrollPane:

1. Create the component to be scrolled.
2. Create an instance of JScrollPane, passing to it the object to scroll.
3. Add the scroll pane to the content pane.

Example:

import java.awt.*;
import javax.swing.*;
public class ScrollPane extends JApplet
{
public void init()
{
try
{
SwingUtilities.invokeAndWait(new Runnable()
{
public void run()
{
makeGUI();
}
}
);
}
catch (Exception exc)
{
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI()
{
JPanel jp = new JPanel();
jp.setLayout(new GridLayout(20, 20));
int b = 0;
for(int i = 0; i < 20; i++) {
for(int j = 0; j < 20; j++) {
jp.add(new JButton("Button " + b));
++b;
}
}
JScrollPane jsp = new JScrollPane(jp);
add(jsp, BorderLayout.CENTER);
}
}