2009-11-23 87 views
15

在JTable中,如何让一些行自动增加高度以显示完整的多行文本?这是它是如何在此刻显示:自动调整JTable中行的高度

我不想设定高度所有行,但仅适用于具有多行文本的人。

回答

32

确切知道行高的唯一方法是渲染每个单元格以确定渲染高度。你的表填充数据后,你可以这样做:

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

如果只有第一列可以包含多个行,您可以优化上述代码只列。

+1

我需要一个表模型吗? – Wulf 2013-06-14 00:06:46

+0

为什么要捕捉ClassCastException?没有演员或任何未经检查的操作。 – 2015-09-22 16:21:26

+0

@KarlRichter,好点,不知道为什么它那里。 try/catch已被删除。 – camickr 2015-09-22 20:30:08

1

您必须迭代每一行,获取每个元素的边界框并相应地调整高度。在标准的JTable中没有对此的代码支持(针对Java的see this article for a solution ... 1.3.1 = 8 * O)。

1

Camickr的解决方案根本不适用于我。我的数据模型是动态的 - 它一直都在变化。我想所提到的解决方案适用于静态数据,如来自数组。

我有JPanel的单元格渲染器组件,它的首选大小在使用prepareRenderer(...)后没有正确设置。在包含的窗口已经可见并且重新绘制(实际上在一些未指定的时间(尽管很短时间)之后2次)后尺寸被正确设置。我怎么能调用上面显示的updateRowHeights()方法,然后我会在哪里执行此操作?如果我在(重写)Table.paint()中调用它,它显然会导致无限重绘。我花了2天。从字面上看。适用于我的解决方案是这一个(这是我用于列的单元格渲染器):

public class GlasscubesMessagesTableCellRenderer extends MyJPanelComponent implements TableCellRenderer { 

    @Override 
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, 
      int row, int column) { 
     //this method updates GUI components of my JPanel based on the model data 
     updateData(value); 
     //this sets the component's width to the column width (therwise my JPanel would not properly fill the width - I am not sure if you want this) 
     setSize(table.getColumnModel().getColumn(column).getWidth(), (int) getPreferredSize().getHeight()); 

     //I used to have revalidate() call here, but it has proven redundant 

     int height = getHeight(); 
     // the only thing that prevents infinite cell repaints is this 
     // condition 
     if (table.getRowHeight(row) != height){ 
      table.setRowHeight(row, height); 
     } 
     return this; 
    } 
} 
+1

您可以像[this]一样动态设置RowHeight(http://stackoverflow.com/questions/21723025/how-to-set-the-rowheight-dynamically-in-a-jtable)。 – GAVD 2016-05-11 09:45:39

+0

谢谢GAVD。哦,我尝试过;)不幸的是,TableModelListener的事件是表模型的事件,而不是表格GUI。在GUI重新绘制之前它们会长/长/ GUI组件的大小已经正确计算。你可以在这一点上强制计算尺寸(我无法弄清楚2天),但你为什么?无论如何,重漆会完成这项工作。我知道这个解决方案很肮脏,但在完美主义消退2天之后,你知道;) – ed22 2016-05-11 09:57:51