3

I'm building a Swing application in Java using NetBeans and I have a problem with layout. My main frame contains a JScrollPane which contains a JPanel called contentPanel which in turn contains a JPanel called listPanel. The listPanel is empty when the program starts, but when the user interacts with the program an unpredictable number of smaller JPanels are added to it. I've used the NetBeans GUI-builder to snap the top edge of listPanel to the top of contentPanel, and the same with the bottom edges.

The problem I have is that when more components are added to listPanel the vertical scrollbar doesen't appear on my scrollpane. The verticalScrollBarPolicy of my scrollpane is set to AS_NEEDED and its viewportView is set to contentPanel. What I think I need to do is to make contentPanel grow when more items are added to listPanel.

Viktor Dahl
  • 1,942
  • 3
  • 25
  • 36

2 Answers2

3

The problem I have is that when more components are added to listPanel the vertical scrollbar doesen't appear on my scrollpane.

The scrollbar will appear when the preferred size of the component added to the scrollpane is greater than the size of the scrollpane. When you add components dynamically you need to tell the scrollpane something has changed. So you basic code should be:

panel.add( subPanel );
panel.revalidate();

Or, because you are adding a panel to the sub panel, you may need to revalidate the scrollpane (I don't remember):

panel.add( subPanel );
scrollPane.revalidate();   

The key is the revalidate() which tell the layout manager to recalculate its size.

camickr
  • 321,443
  • 19
  • 166
  • 288
1

Use a different LayoutManager. One that will allow for vertical growth like BoxLayout. Also remember that you can use multiple layouts and nest them inside of each other for different effects.

jzd
  • 23,473
  • 9
  • 54
  • 76
  • The listPanel is using a BoxLayout, do you mean I should use one in contentPanel as well? – Viktor Dahl Mar 04 '11 at 14:06
  • 1
    @Viktor, since you have nested panels you need to look at possibly adjusting the Layout on each level. The contentPanel layout is going to be a factor as well as the layouts and preferred sizes of items inside of the contentPanel. – jzd Mar 04 '11 at 14:25