Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto adjust the height of rows in a JTable

Tags:

java

swing

In a JTable, how can I make some rows automatically increase height to show the complete multiline text inside? This is how it is displayed at the moment:

I do not want to set the height for all rows, but only for the ones which have multiline text.

like image 954
AndreaC Avatar asked Nov 23 '09 14:11

AndreaC


People also ask

How do you size a JTable?

This can be done easily using these two methods of the JTable class: setRowHeight(int row, int rowHeight): sets the height (in pixels) for an individual row. setRowHeight(int rowHeight): sets the height (in pixels) for all rows in the table and discards heights of all rows were set individually before.

What is JTable TableModel?

The TableModel interface specifies the methods the JTable will use to interrogate a tabular data model. The JTable can be set up to display any data model which implements the TableModel interface with a couple of lines of code: TableModel myData = new MyTableModel(); JTable table = new JTable(myData);

How do you make a JTable column not editable?

Right-click on the table cells. From popup menu, choose "Table Contents..". Uncheck the editable check box for the column you want to make it non-editable.


1 Answers

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.

like image 75
camickr Avatar answered Sep 23 '22 10:09

camickr