This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
The moose likes Swing / AWT / SWT and the fly likes JTable-JScrollPane Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "JTable-JScrollPane" Watch "JTable-JScrollPane" New topic
Author

JTable-JScrollPane

Manuel Paco
Ranch Hand

Joined: Sep 23, 2001
Posts: 58
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

Joined: Oct 18, 2000
Posts: 4121

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


-Nate
Write once, run anywhere, because there's nowhere to hide! - /. A.C.
Manuel Paco
Ranch Hand

Joined: Sep 23, 2001
Posts: 58
Thanks Nathan
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: JTable-JScrollPane