http://book.77169.org/ask9/ask158152.htm
public class TableUtil {
/**
* use column's value to get the column width
*
* @param table
* @param icol
* @return
*/
public static int getPreferredWidthForCloumn(JTable table, int icol) {
TableColumnModel tcl = table.getColumnModel();
TableColumn col = tcl.getColumn(icol);
int c = col.getModelIndex(), width = 0, maxw = 0;
for (int r = 0; r < table.getRowCount(); ++r) {
TableCellRenderer renderer = table.getCellRenderer(r, c);
Component comp = renderer.getTableCellRendererComponent(table,
table.getValueAt(r, c), false, false, r, c);
width = comp.getPreferredSize().width;
maxw = width > maxw ? width : maxw;
}
return maxw;
}
}
private void setTableWidthAuto(JTable table) {
for (int i = 0; i < table.getColumnCount(); i++) {
int with = TableUtil.getPreferredWidthForCloumn(table, i) + 5;
table.getColumnModel().getColumn(i).setPreferredWidth(with);
}
}