views:

200

answers:

3

Hi All,

I'd like to use a JScrollPane for a panel which has an arbitrary list of labels in it using box layout. I'm trying to get it so that the scrollbar would appear if there were too many items (labels) to display.

I tried adding a JScrollPane to the panel and then add the labels but then I don't see any scroll bar.

Any ideas?

TIA

+1  A: 

For this kind of thing, you'd normally use a JList or JTable (if you need custom rendering).

Michael Borgwardt
Yes I could. I am considering this. In my case this is a game which is keyboard oriented so it's a fair amount more code to implement with a List over a set of labels. But you are right. I could do it this way.
Dan Howard
+1  A: 

Make sure that you call validate() or revalidate() on the JScrollPane after adding an item, to force the preferred size of the panel to be recalculated.

finnw
That didn't seem to work for me. See below.
Dan Howard
A: 

Here's how I did it.

JPanel midPanel = new JPanel();
midPanel.setLayout(new BoxLayout(midPanel, BoxLayout.Y_AXIS));
midPanel.add(new JLabel("<html><u>Label</u>"));
Box box = Box.createVerticalBox();
for (Item item : data.getInventory()) {
    inventory.add(box.add(new JLabel(item.getName())));
}

JScrollPane jscrlpBox = new JScrollPane(box);
midPanel.add(jscrlpBox);
add(midPanel, BorderLayout.CENTER);

From:

http://www.java2s.com/Code/Java/Swing-JFC/JScrollPanetoholdscrollablecomponent.htm

Dan Howard