Java Reference
In-Depth Information
Changing the Viewport View
If you've created a JScrollPane with an associated component to scroll, you just need to add
the JScrollPane to the display, and it's ready to go. If, however, you didn't associate a compo-
nent at creation time, or just want to change it later, there are two ways to associate a new
component to scroll. First, you can directly change the component to scroll by setting the
viewportView property:
scrollPane.setViewportView(dogLabel);
The other way of changing the component to scroll involves centering the JViewport
within the JScrollPane and changing its view property:
scrollPane.getViewport().setView(dogLabel);
You'll learn more about JViewport components in the “JViewport Class” section later in
this chapter.
Scrollable Interface
Unlike the AWT components such as List , which automatically provide a scrollable area when the
choices are too numerous to display at once, Swing components JList , JTable , JTextComponent ,
and JTree don't automatically provide scrolling support. You must create the component, add
it to a JScrollPane , and then add the scroll pane to the screen.
JList list = new JList(...);
JScrollPane scrollPane = new JScrollPane(list);
aFrame.add(scrollPane, BorderLayout.CENTER);
The reason that adding a component to a JScrollPane works is that each of the Swing
components that might be too large for the screen (and require scrolling support) implements
the Scrollable interface. With this interface implemented, when you move the scrollbars
associated with the JScrollPane , the JScrollPane asks the Scrollable component within the
container for its sizing information to properly position the component based on the current
scrollbar positions.
The only time you need to worry about the Scrollable interface is when you're creating
a new custom component that requires scrolling support. The following is the Scrollable
interface definition.
public interface Scrollable {
public Dimension getPreferredScrollableViewportSize();
public boolean getScrollableTracksViewportHeight();
public boolean getScrollableTracksViewportWidth();
public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation,
int direction);
public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation,
int direction);
}
Search WWH ::




Custom Search