Thursday, July 31, 2008

Code to set a Jtable column to fit its contents

Code to set a column to fit its contents,


TableColumn column = table.getColumnModel().getColumn(columnIndex);
int w = column.getWidth();
int n = table.getRowCount();
for (int i = 0; i < n; i ++)
{
TableCellRenderer r = table.getCellRenderer(i, this.columnIndex);
Component c = r.getTableCellRendererComponent(
table,
table.getValueAt(i, columnIndex),
false,
false,
i,
columnIndex);
w = Math.max(w, c.getPreferredSize().width);
}
column.setPreferredWidth(w);