自动调整JTable列的宽度

我有一个有3列的JTable:

- No. # - Name - PhoneNumber 

我想为每列制作特定的宽度,如下所示:

在此处输入图像描述

我希望JTable能够在需要时动态更新其列的宽度(例如,在#列中插入大数字)并保持JTable的相同样式

我使用以下代码解决了第一个问题:

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

但是,如果列的当前宽度不适合其内容,我只能使myTable动态更新宽度。 你能帮我解决这个问题吗?

在这里,我找到了答案: 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 ); } 

使用DefaultTableModel的addRow(…)方法动态地向表中添加数据。

更新:

要调整可见列的宽度,我认为您需要使用:

 tableColumn.setWidth(...); 

我实际上也遇到了这个问题。 我找到了一个解决了我的问题的有用链接。 几乎得到特定列并将其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