Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

JTable-JScrollPane

 
Manuel Paco
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please help.
I would like to get a table with columnHeads, rows and scrollbars.
The following code does not show scrollbars.
table = new JTable( rows, columnHeads );
JScrollPane scrollpane = new JScrollPane( table );
getContentPane().add( scrollpane, BorderLayout.CENTER );
The following code does show scrollbars but does not show "columnHeads".
table = new JTable( rows, columnHeads );
JPanel panelTable = new JPanel();
panelTable.add(table);
JScrollPane scrollpane = new JScrollPane( panelTable );
getContentPane().add( scrollpane, BorderLayout.CENTER );
What am I doing wrong?
 
Nathan Pruett
Bartender
Posts: 4121
IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are on the right track! You have to add the table to a scrollpane to get both of these to show up on the table. However, the scrollpane only shows scrollbars if the contained component ( the table ) is larger than the displayed size. Since you are adding all this to the center area of a BorderLayout, everything is being displayed at it's preferred size, and the scrollpanel thinks the scrollbars are not needed. There are two solutions to your problem. First, you could just tell the scrollpane to show scrollbars, no matter what, with :



You can also tell the table to set the preferred size of the scrollpane that contains it. This makes the scrollpane smaller, and it still only shows the scrollbars that are needed.



Where w is the width you want, and h is the height. You can tailor this somewhat to the size of the screen or table by doing frame.getWidth(), or getting sizes from the TableModel or TableColumnModel to get sizes of rows and columns, and the number of them in the model. ( So you can say that you want the height to be the height of 5 table rows and the width to be the width of all the columns or whatever... )

Hope this helps,
-Nate
 
Manuel Paco
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Nathan
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic