JScrollPane Blunders: Part 1

I have now witnessed one too many JScrollPane tragedies. I hope this helps.

Blunder #1 – One Giant Scroll Pane

Without a scroll pane, your Swing GUI probably looks fine at its default size. But those pesky users might try something exotic…like resizing the window. So you add a scroll pane to handle resizing gracefully. After all, scroll bars are better than vanishing components.

Here is a trivial window at its preferred size:

Big Scroll 1

And here is what happens when you make it a bit smaller…notice the scrolling:

Big Scroll 2

But the scroll pane encloses too much, which is blunder #1. The tabs even scroll away:

Big Scroll 3

When you see resizing problems, wrapping the entire panel with one giant JScrollPane is usually wrong. Most screens contain things like buttons or tabs that should not scroll.

A Small Improvement

With JTabbedPane, you generally want scroll panes inside each tab. This is a very trivial change:

Big Scroll 4

Now, the tabs do not scroll off the edge of the screen. This GUI is far from ideal, however. I found that changing the horizontal scrolling policy to JScrollPane.HORIZONTAL_SCROLLBAR_NEVER slightly improves this screen:

Big Scroll 5

Now you only see vertical scrolling. The text fields may get clipped horizontally, but only if the user makes this screen tiny.

Bonus Points?

I suppose you could really go nuts and make the text fields squish horizontally if the panel gets too narrow, but still scroll vertically as shown. I tinkered with that for a few minutes, but didn’t have much luck. One idea is to create a panel class that implements Scrollable to obtain fine-grained control over the horizontal resize behavior. Suggestions are welcome.

(Real apps usually have much bigger panels so you’ll end up with scroll panes around tables or text areas, giving your screens more natural places to expand and contract…the screen shown here is pretty unrealistic. Wrapping labels with scroll panes should be rare.)

Tease…

In coming days I plan to show at least two common scroll pane blunders. Stay tuned! Or better yet, subscribe to my Atom feed.


Dan Lewis Says:

It’s time to consider a Swing book. You are the “Ericle”. (Kind of sounds like “Goracle”, get it?).

[...] is the final “blunder” of this series. In Part 1, I showed how wrapping the entire screen in one giant scroll pane is usually a bad idea. Part 2 [...]

[...] three-part series by Eric Burke on do’s and do not’s of scroll panes. Read part 1, part 2 and part 3. A good rule of thumb would be to never use scroll panes for wrapping UI [...]