Java: Have a JTable’s column preferred width adjusted perfectly to the size of the longest string in the model

Here’s a utility method I’ve coded for FrostWire’s partial download dialog. With it I’m able to adjust a JTable’s column by iterating over the table’s column model data and calculating the exact dimensions required to render the longest string found. You can specify a maximum width (to avoid some really long strings from screwing up the display) and some right padding in case you need some breathing room.

Enjoy

[java]
/**
* It will adjust the column width to match the widest element.
* (You might not want to use this for every column, consider some columns might be really long)
* it assumes model and jtable != null
*/
public static void adjustColumnWidth(TableModel model, int columnIndex, int maxWidth, int rightPadding, JTable table) {

if (columnIndex > model.getColumnCount()-1) {
//invalid column index
return;
}

if (!model.getColumnClass(columnIndex).equals(String.class)) {
return;
}

String longestValue = “”;
for (int row = 0; row < model.getRowCount(); row++) { String strValue = (String) model.getValueAt(row, columnIndex); if (strValue != null && strValue.length() > longestValue.length()) {
longestValue = strValue;
}
}

Graphics g = table.getGraphics();

try {
int suggestedWidth = (int) g.getFontMetrics(table.getFont()).getStringBounds(longestValue, g).getWidth();
table.getColumnModel().getColumn(columnIndex).setPreferredWidth(((suggestedWidth > maxWidth) ? maxWidth : suggestedWidth)+rightPadding);
} catch (Exception e) {
table.getColumnModel().getColumn(columnIndex).setPreferredWidth(maxWidth);
e.printStackTrace();
}

}
[/java]

Note, make sure you invoke this guy only once, usually after the table has been first painted (you could override paint()) or after the model data has been updated (if it gets to be updated and you feel like autoadjusting a particular column)

Leave a Reply

Your email address will not be published. Required fields are marked *