Auto adjust the height of rows in a JTable

The only way to know the row height for sure is to render each cell to determine the rendered height. After your table is populated with data you can do:

private void updateRowHeights()
{
    for (int row = 0; row < table.getRowCount(); row++)
    {
        int rowHeight = table.getRowHeight();

        for (int column = 0; column < table.getColumnCount(); column++)
        {
            Component comp = table.prepareRenderer(table.getCellRenderer(row, column), row, column);
            rowHeight = Math.max(rowHeight, comp.getPreferredSize().height);
        }

        table.setRowHeight(row, rowHeight);
    }
}

If only the first column can contain multiple line you can optimize the above code for that column only.

Leave a Comment