Shrink JScroll Pane to same Height as JTable

Viewed 12693

I currently have JTables nested in JScrollPanes like so:

enter image description here

My problem is that the number of rows in each table is variable when the table is created. What I want to do is make the JScrollpane smaller if the table is too short, but I want to keep it at a set size if the table is too long.

How can I accomplish this?

5 Answers

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) ));
  1. The header line is not necessarily table.getRowHeight() pixels in height. (In the "Metal" L&F, it is taller)
  2. A vertical scrollbar in the scrollPane will squish the table smaller than it's preferred size.
  3. A horizontal scrollbar will take additional space, so not all requested 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.

JTable with and without scrollbar

Related