Yossale
Yossale

Reputation: 14361

SWING JTable: How do I make each row as high as it's tallest object?

I have a table , where some objects are rendered and are of non-fixed size (list of attributes). I want each row to be as high as it's tallest object , and I was wondering of to do it. I thought about doing something like this (see below) , but I'm sure there's something better..

public Component getTableCellRendererComponent(JTable table, Object value,
                                                 boolean isSelected,
                                                 boolean hasFocus, int row,
                                                 int column)
  {
      /*....*/

      this.setListData((Object[])value);
      int height = new Double(getPreferredSize().getHeight()).intValue();
      if (table.getRowHeight(row) < height)
          table.setRowHeight(row, height);    
      /*....*/

      return this;
  }

Upvotes: 1

Views: 787

Answers (2)

camickr
camickr

Reputation: 324078

You should not have code like that in a renderer. Instead, when you load the data into the model, do something like:

private void updateRowHeights()
{
    try
    {
        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);
        }
    }
    catch(ClassCastException e) {}
}

Upvotes: 1

jzd
jzd

Reputation: 23629

I would stick with the solution you have. I don't think there is a simpler way to do this. No matter what you are going to have the check the height of each cell, so you might as well do that as you render each one.

Upvotes: 0

Related Questions