I am trying to resize my columns based on both column headers and column width.
I have had some success with this, however it is only a temporary solution really.
The min width I'm setting is only for one table, however I am previewing many tables with different column headers, so sometimes this min width will be too small. I wanted a way of getting the column header width for the smallest column header and assign it to this variable.
final TableColumnModel columnModel = table.getColumnModel();
for (int column = 0; column < table.getColumnCount(); column++)
{
int width = 70; // Min width
for (int row = 0; row < table.getRowCount(); row++)
{
TableCellRenderer renderer = table.getCellRenderer(row, column);
Component comp = table.prepareRenderer(renderer, row, column);
width = Math.max(comp.getPreferredSize().width +1 , width);
}
columnModel.getColumn(column).setPreferredWidth(width);
}
UPDATE:
I have tried using the DefaultTableCellRenderer for the column it is looping through, then getting the column header width and applying that to the variable, but it came with this result
final TableColumnModel columnModel = table.getColumnModel();
for (int column = 0; column < table.getColumnCount(); column++)
{
DefaultTableCellRenderer colwidth=((DefaultTableCellRenderer)table.getTableHeader().getDefaultRenderer());
int width = colwidth.getWidth();
for (int row = 0; row < table.getRowCount(); row++)
{
TableCellRenderer renderer = table.getCellRenderer(row, column);
Component comp = table.prepareRenderer(renderer, row, column);
width = Math.max(comp.getPreferredSize().width +1 , width);
}
columnModel.getColumn(column).setPreferredWidth(width);
}