The JScrollPane Class

The JScrollPane class offers a more flexible version of the ScrollPane class found in the AWT package. Beyond the automatic scrollbars, you can put in horizontal and vertical headers as well as active components in the corners of your pane. (Figure 11-6 shows the exact areas available in a JScrollPane, which is managed by the ScrollPaneLayout class.)

Many Swing components use JScrollPane to handle their scrolling. The JList component, for example, does not handle scrolling on its own. Instead, it concentrates on presenting the list and making selection easy, assuming you’ll put it inside a JScrollPane if you need scrolling. Figure 11-3 shows a simple JScrollPane in action with a JList object.

JScrollPane showing two portions of a list that is too long for one screen

Figure 11-3. JScrollPane showing two portions of a list that is too long for one screen

This particular example does not take advantage of the row or column headers. The scrollpane adds the scrollbars automatically, but only “as needed.” If we were to resize the window to make it much larger, the scrollbars would become inactive. Here’s the code that builds this pane:

// ScrollList.java // A simple JScrollPane // import javax.swing.*; import java.awt.*; public class ScrollList extends JFrame { JScrollPane scrollpane; public ScrollList( ) { super("JScrollPane Demonstration"); setSize(300, 200); setDefaultCloseOperation(EXIT_ON_CLOSE); String categories[] = { "Household", ...

Get Java Swing, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.