TableModel model = getModel();
TableColumn column = null;
Component comp = null;
int headerWidth = 0;
TableCellRenderer headerRenderer = getTableHeader().getDefaultRenderer();
for (int columnIndex = 0; columnIndex < model.getColumnCount(); columnIndex++) {
int cellWidth = 0;
column = getColumnModel().getColumn(columnIndex);
comp = headerRenderer.getTableCellRendererComponent(
null, column.getHeaderValue(),
false, false, 0, 0);
headerWidth = comp.getPreferredSize().width;
TableCellRenderer renderer = getCellRenderer(0, columnIndex);
int rowCount = Math.min(model.getRowCount(), 10);
for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) {
Object value = model.getValueAt(rowIndex, columnIndex);
comp = renderer.getTableCellRendererComponent(
this, value,
false, false, rowIndex, columnIndex);
cellWidth = Math.max(comp.getPreferredSize().width, cellWidth);
}
column.setPreferredWidth(Math.max(headerWidth, cellWidth));