简体   繁体   English

SWING JTable:如何使每一行与它的最高对象一样高?

[英]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. 不管您要检查每个单元格的高度如何,因此在渲染每个单元格时也可以这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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