Monday, June 9, 2014

A Side-Scrolling JList

I just spent a less-than-enjoyable chunk of time trying to get a JList to scroll (horizontally) in a Java application with a Swing GUI. Everything I found in an online search either made it seem easier than it actually turned out to be (by omitting the key ingredient in the recipe) or sent me off in unproductive directions. So I'm recording what worked because I will, with probability 1.0, forget it soon enough.

The structure of the program, omitting most details, looked like this:

JList wideList = functionThatSpitsUpWideList();
JScrollPane pane = new JScrollPane(wideList);
JOptionPane.showMessageDialog(parent, pane, title, JOptionPane.PLAIN_MESSAGE);

It produced a dialog with a mile-wide list and no scroll bars. I tried what I thought was the obvious remedy, invoking setMaximumSize() (with modest dimensions) first on wideList and then on pane. Neither helped. The answer turned out to be invoking setPreferredSize() on pane:

JList wideList = functionThatSpitsUpWideList();
JScrollPane pane = new JScrollPane(wideList);
pane.setPreferredSize(new Dimension(400, 200));
JOptionPane.showMessageDialog(parent, pane, title, JOptionPane.PLAIN_MESSAGE);

I (naively?) thought that the maximum size trumps the preferred size. Oops.

No comments:

Post a Comment

Due to intermittent spamming, comments are being moderated. If this is your first time commenting on the blog, please read the Ground Rules for Comments. In particular, if you want to ask an operations research-related question not relevant to this post, consider asking it on Operations Research Stack Exchange.