You can try the following code:
/**
* Sets the preferred width of the columns of a table from prototypes
* @param table the target table
* @param prototypes an array of prototypes, {@code null} values will be ignored
* @param setMaxWidth {@code true} if the maximum column width should also be set
*/
public static void setWidthFromPrototype(JTable table, Object[] prototypes, boolean setMaxWidth) {
if (prototypes.length != table.getColumnCount())
throw new IllegalArgumentException("The prototypes array should contain exactly one element per table column");
for (int i = 0; i < prototypes.length; i++) {
if (prototypes[i] != null) {
Component proto = table.getCellRenderer(0,i)
.getTableCellRendererComponent(table, prototypes[i], false, false, 0, i);
int prefWidth = (int) proto.getPreferredSize().getWidth() + 1;
table.getColumnModel().getColumn(i).setPreferredWidth(prefWidth);
if (setMaxWidth)
table.getColumnModel().getColumn(i).setMaxWidth(prefWidth);
}
}
}