2011-06-23 61 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