• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

JTable-JScrollPane

 
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Bartender
Posts: 4121
IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Nathan
reply
    Bookmark Topic Watch Topic
  • New Topic