简体   繁体   中英

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;
  }

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) {}
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM