我有一个包含 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);
}