Resize a Jtable Vertically based on it's content

I have a view in my java project that needs to resize a table. I have n number of Jtables inside a JScrollPane. Some of them doesn't have enough rows to fill the total size of the table. The best solution I think would be to resize the table to fill to the number of rows that were allocated.

1) The table has a dimension of 4x4 but if there is not enough rows (i.e, less than 4) it will have a gap, which I don't want.

Since this table is static and won't be changed how can I resize this table programmatically based on the number of rows that it will have, like having 1, 2 or only 3 rows and not have this gap?

PS: I know how many rows it will have, I just don't know how to resize the table height programmatically during runtime.

TableModel

Upvotes: 1

Views: 1566

Answers (2)

camickr
camickr

Reputation: 324098

Since this table is static and won't be changed how can I resize this table programmatically based on the number of rows that it will have,

After adding all the data to the table you can use:

table.setPreferredScrollableViewportSize(table.getPreferredSize());

Then when the table is added to the scroll pane the size of the scroll pane will be the preferred size of the table.

Upvotes: 2

ItamarG3
ItamarG3

Reputation: 4122

To make the JTable stretch to fit the height of the view, you can call:

table.setFillsViewportHeight(true);

from the javadoc:

Sets whether or not this table is always made large enough to fill the height of an enclosing viewport.

Upvotes: 1

Related Questions