I currently have JTables nested in JScrollPanes like so:
My problem is
The following (currently accepted) code does not take into account various aspects of the Look and Feel:
Dimension d = table.getPreferredSize();
scrollPane.setPreferredSize(
new Dimension( d.width, table.getRowHeight() * (rows+1) ));
table.getRowHeight()
pixels in height. (In the "Metal" L&F, it is taller)scrollPane
will squish the table smaller than it's preferred size.rows
rows will be visible.The following code should be used instead:
table.setPreferredScrollableViewportSize(
new Dimension(
table.getPreferredSize().width,
table.getRowHeight() * visible_rows));
The scrollPane
will ask the table for its preferred size, and adds to that any extra space for the header and scrollbars.
Below shows the difference in a JTable
with 4 rows, when visible_rows
is reduced from 4
to 3
. The preferred width of the JScrollPane
is automatically padded to include the scrollbar instead of compacting the table columns. Also note room for the header (which is different from the row height) is also automatically provided; it is not included in the visible_rows
count.
Dimension d = table.getPreferredSize();
scrollPane.setPreferredSize(
new Dimension(d.width,table.getRowHeight()*rows+1));
Where rows
represents the number of rows of data, or the limit.
I use setPreferredScrollableViewportSize() in this context, followed by pack()
or revalidate()
as required.
Addendum:
How do you use it?
It's a feature of the implementation of Scrollable in JTable
. Here are several examples. The complementary getPreferredScrollableViewportSize()
may also be useful.
Use a GridBagLayout manager and set the maximum size of the JScrollPane to whatever you want to. If the table is larger the JScroll won't grow beyond that size.
Then, add a glue component ( I think it is something like BoxLayout.createVerticalGlue or something like that ) which is an empty component that just takes the remaining space.
So, when the table is smaller, this component will take the remaining space, if the table is larger, it won't take anything since the JScrollPane is using it.
If you use MigLayout, when add the scrollpane containing the JTable, you can specify the constraint growx
instead of grow
, to make it stretch only horizontally.
Now the scrollpane is located in the middle of its parent. You can set in the row constraint to make it align to top
of the row. Or, in component constraint: aligny top
.