Shrink JScroll Pane to same Height as JTable

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.


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