2011-06-23 132 views
9

我有一個JTable 3列:自動調整的JTable中列的寬度動態

- No. # 
- Name 
- PhoneNumber 

我想提出具體的寬度爲每列如下:

enter image description here

,我想如果需要,JTable能夠動態更新其列的寬度(例如,在列#中插入大數字)並保留相同樣式的JTable

我解決了第一個問題,使用此代碼:

myTable.getColumnModel().getColumn(columnNumber).setPreferredWidth(columnWidth); 

但我沒有成功,使myTable的更新動態寬度只有在列的當前寬度不適合的內容。你能幫我解決這個問題嗎?

回答

13

在這裏,我發現我的回答:http://tips4java.wordpress.com/2008/11/10/table-column-adjuster/
的想法是要檢查一些行內容長度來調整列寬。
在文章中,作者在可下載的java文件中提供了完整的代碼。

JTable table = new JTable(...); 
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); 

for (int column = 0; column < table.getColumnCount(); column++) 
{ 
    TableColumn tableColumn = table.getColumnModel().getColumn(column); 
    int preferredWidth = tableColumn.getMinWidth(); 
    int maxWidth = tableColumn.getMaxWidth(); 

    for (int row = 0; row < table.getRowCount(); row++) 
    { 
     TableCellRenderer cellRenderer = table.getCellRenderer(row, column); 
     Component c = table.prepareRenderer(cellRenderer, row, column); 
     int width = c.getPreferredSize().width + table.getIntercellSpacing().width; 
     preferredWidth = Math.max(preferredWidth, width); 

     // We've exceeded the maximum width, no need to check other rows 

     if (preferredWidth >= maxWidth) 
     { 
      preferredWidth = maxWidth; 
      break; 
     } 
    } 

    tableColumn.setPreferredWidth(preferredWidth); 
} 
1

使用DefaultTableModel的addRow(...)方法將數據動態添加到表中。

更新:

要調整可見列,我認爲你需要使用的寬度:

tableColumn.setWidth(...); 
+0

哎呀,我要讓JTable中動態更新的寬度,但我寫的使JTable動態更新,對不起 –

+0

@Eng Fouad,請參閱更新。 – camickr

+1

順便說一句,接受的答案實際上是你的;) – Matthieu

0

我也遇到過這個問題。我找到了一個有用的鏈接來解決我的問題。 差不多得到特定的列並設置其setMinWidth和setMaxWidth是相同的(如固定)

private void fixWidth(final JTable table, final int columnIndex, final int width) { 
    TableColumn column = table.getColumnModel().getColumn(columnIndex); 
    column.setMinWidth(width); 
    column.setMaxWidth(width); 
    column.setPreferredWidth(width); 
} 

編號:https://forums.oracle.com/thread/1353172