1

I want to add different buttons, vertically stacked, to a JPanel at run-time and use a JScrollPane so that all buttons will be visible (with some scrolling).

In order to do this, I have added my JPanel to a JScrollPane, after which I add buttons to my JPanel.

However, when I do this the vertical scrollbar does not allow me to see all images. For example when I add 7 buttons I can only scroll to see 5 full images and half of the 6 images.

Why doesn't my scrollbar allow me to display all 7 buttons?

Mark Elliot
  • 75,278
  • 22
  • 140
  • 160
PPB
  • 287
  • 3
  • 7
  • 19

2 Answers2

9

Create the panel and scrollpane like:

JPanel panel = new JPanel();
JScrollPane scrollPane = new JScrollPane( panel );

When you add buttons to the panel at run time the code should be:

panel.add( button );
panel.revalidate();

As long as you are using a layout manager the preferred size will be recalculated and the scrollbar will appear.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • Better to revalidate the scroll pane. Revalidating the panel does not always work. – finnw Feb 17 '10 at 20:20
  • I've never had a problem. Make sure the code is done on the EDT. Make sure you haven't hard coded the preferred size of the panel. – camickr Feb 17 '10 at 21:41
3

Make scroll pane a wrapper over your panel - new JScrollPane (myPanel) and add it instead of naked panel in your panel's container.

You also may want to play with its setPreferredSize() method.

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
Roman
  • 64,384
  • 92
  • 238
  • 332