• Post Reply Bookmark Topic Watch Topic
  • New Topic

why JScrollPane is not packed as to is its content  RSS feed

 
Yuan Ye
Ranch Hand
Posts: 172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I use "JScrollPane scPane = new JScrollPane(table);" statement to assign a scrollPane to a Jtable. However when I add the scrollPane to anyother JPanel. The height of the scrollPane is much larger than the table htight.
Why would that happen. I thought a container should automatically resize according to its content. How can I solve this problem? Thanks.
 
Ken Blair
Ranch Hand
Posts: 1078
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sounds like it's the layout manager the container you add the JScrollPane to is using. JPanel uses a FlowLayout, the scrollpane is going to size itself as small as the table and the extra will be empty, however, other containers use other layouts such as BorderLayout, in which case the ScrollPane would take up all the available space and hence it could be much bigger than the table. Try this... add a JButton to a container that's much bigger than the button is using FlowLayout, then try it using BorderLayout, you'll see what I mean. In on the button will be as big as it needs to and the rest of the space will be empty, in border it will take up all available space.
If you're wondering why your container holding the JScrollPane is not scaling itself to the size of the scrollpane then try calling pack() on THAT container after you've packed the scrollpane.
 
Nathan Pruett
Bartender
Posts: 4121
IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This issue deals more with the interaction between JScrollPanes and the Scrollable interface. For some reason the default JTable implementation of getPreferredScrollableViewportSize() returns an annoyingly large size. The way I usually get a good size is compute the size of the columns and how many rows I want to show up, and pass this into setPreferredScrollableViewportSize()...

 
Yuan Ye
Ranch Hand
Posts: 172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nathan, You are right. Thanks for your code fragment. I solved the problem by using it.
Ken, also thank you for your opinion.
 
Ken Blair
Ranch Hand
Posts: 1078
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ahhh I thought the scrollpane was showing up larger than the table.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!