2009-11-23 85 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