日期:2014-05-20 浏览次数:20719 次
/**
* 自动调整表列宽度
*
* @param table 被调整表
* @param addtionalSpace 额外的宽度
* @return 总列宽
*/
public static int fitTableColumnsWidth(JTable table, int addtionalSpace) {
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
JTableHeader header = table.getTableHeader();
int rowCount = table.getRowCount();
Enumeration columns = table.getColumnModel().getColumns();
int totalColumnWidth = 0;
while (columns.hasMoreElements()) {
TableColumn column = (TableColumn) columns.nextElement();
int col = header.getColumnModel().getColumnIndex(column.getIdentifier());
int width = (int) table.getTableHeader().getDefaultRenderer()
.getTableCellRendererComponent(table, column.getIdentifier()
, false, false, -1, col).getPreferredSize().getWidth();
for (int row = 0; row < rowCount; row++) {
int preferedWidth = (int) table.getCellRenderer(row, col).getTableCellRendererComponent(table,
table.getValueAt(row, col), false, false, row, col).getPreferredSize().getWidth();
width = Math.max(width, preferedWidth);
}
header.setResizingColumn(column); // this line is very important
column.setWidth(width + table.getIntercellSpacing().width + addtionalSpace);
totalColumnWidth += width + table.getIntercellSpacing().width + addtionalSpace;
}
return totalColumnWidth;
}