a table, or a group of components contained within another lightweight container, such as a
JPanel. In either case, 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 behavior, a JScrollPane will dynamically add or remove a scroll bar as needed. For
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. The one used in this chapter is shown here:
JScrollPane(Component comp)
The component to be scrolled is specified by comp. Scroll bars are automatically displayed
when the content of the pane exceeds the dimensions of the viewport.
Here are the steps to follow to use a scroll pane:
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.
The following example illustrates a scroll pane. First, a JPanel object is created, and 400
buttons are added to it, arranged into 20 columns. This panel is then added to a scroll pane,
and the scroll pane is added to the content pane. Because the panel is larger than the
viewport, vertical and horizontal scroll bars appear automatically. You can use the scroll
bars to scroll the buttons into view.
// Demonstrate JScrollPane.
import java.awt.*;
import javax.swing.*;
/*
<applet code="JScrollPaneDemo" width=300 height=250>
</applet>
*/
public class JScrollPaneDemo 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);
}
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home