I am having some difficulty resizing columns in a JTable. The code I am using works just fine in I have the Look and Feel set to Nimbus, but any other Look and Feel does not set the column widths based on the code below. Infact I get different results depending on what font has been set.
private void updateColWidths() { try { TableColumnModel columnModel = table1.getColumnModel(); for (int col = 0; col < table1.getColumnCount(); col ++) { int colWidth = 0; for (int row = 0; row < table1.getRowCount(); row ++) { Component comp = table1.prepareRenderer(table1.getCellRenderer(row, col), row, col); colWidth = Math.max(colWidth, comp.getPreferredSize().width); } TableColumn column = columnModel.getColumn(col); TableCellRenderer headerRenderer = column.getHeaderRenderer(); if (headerRenderer == null) { headerRenderer = table1.getTableHeader().getDefaultRenderer(); } Object headerValue = column.getHeaderValue(); Component headerComp = headerRenderer.getTableCellRendererComponent(table1, headerValue, false, false, 0, col); colWidth = Math.max(colWidth, headerComp.getPreferredSize().width); column.setPreferredWidth(colWidth); } } catch(ClassCastException e) {} }
Here are some screen shots of the different look and feels' using Verdana 16 as the font.
Nimbus nimbus.jpg
Metal metal.jpg
Motif motif.jpg
GTK+ GTK.jpg
Any ideas what might be causing this? I'd just leave this with Nimbus, but my Mac users ( it always the Mac users that stir-up trouble ) would like to use their default Look and Feel.