Hello all,
Can someone point me to a technique for optimizing column widths in a
JTable? I would like to load the TableModel with data first, then call
an "optimize" method to resize all the columns based on data and column
headers (whichever is larger).
Any help/advice would be greatly appreciated.
-Mike
Thomas Kellerer - 06 Jan 2004 17:56 GMT
piomice schrieb:
> Hello all,
>
[quoted text clipped - 6 lines]
>
> -Mike
This does not include the column headers, but I'm sure you will be able to
figure it out...
Regards
Thomas
============== snip =========================
Font f = theTable.getFont();
FontMetrics fm = theTable.getFontMetrics(f);
TableColumnModel colMod = theTable.getColumnModel();
TableColumn col = colMod.getColumn(column);
int addWidth = theTable.getAdditionalColumnSpace(0, column);
String s = null;
int optWidth = 0;
int stringWidth = 0;
int rowcount = theTable.getRowCount();
for (int row = 0; row < rowcount; row ++)
{
// !!!!! you have to adapt theTable.!!!!!
s = (String)theTable.getValueAt(row, column);
if (s == null || s.length() == 0)
stringWidth = 0;
else
stringWidth = fm.stringWidth(s);
optWidth = Math.max(optWidth, stringWidth + addWidth);
}
if (optWidth > 0)
{
col.setPreferredWidth(optWidth);
}
Chris Gokey - 06 Jan 2004 18:15 GMT
Here is some code that I found that does a decent job.
-chris
public static void calcColumnWidths(JTable table) {
JTableHeader header = table.getTableHeader();
TableCellRenderer defaultHeaderRenderer = null;
if (header != null)
defaultHeaderRenderer = header.getDefaultRenderer();
TableColumnModel columns = table.getColumnModel();
TableModel data = table.getModel();
int margin = columns.getColumnMargin(); // only JDK1.3
int rowCount = data.getRowCount();
int totalWidth = 0;
for (int i = columns.getColumnCount() - 1; i >= 0; --i) {
TableColumn column = columns.getColumn(i);
int columnIndex = column.getModelIndex();
int width = -1;
TableCellRenderer h = column.getHeaderRenderer();
if (h == null)
h = defaultHeaderRenderer;
if (h != null) // Not explicitly impossible
{
Component c = h.getTableCellRendererComponent(table,
column.getHeaderValue(), false, false, -1, i);
width = c.getPreferredSize().width;
}
for (int row = rowCount - 1; row >= 0; --row) {
TableCellRenderer r = table.getCellRenderer(row, i);
Component c = r.getTableCellRendererComponent(table,
data.getValueAt(row, columnIndex), false, false, row, i);
width = Math.max(width, c.getPreferredSize().width);
}
if (width >= 0)
column.setPreferredWidth(width + margin); // <1.3: without margin
else {
; // ???
}
totalWidth += column.getPreferredWidth();
}
Dimension size = table.getPreferredScrollableViewportSize();
size.width = totalWidth;
table.setPreferredScrollableViewportSize(size);
}
> Hello all,
>
[quoted text clipped - 6 lines]
>
> -Mike
--
piomice - 07 Jan 2004 19:22 GMT
> Hello all,
>
[quoted text clipped - 6 lines]
>
> -Mike
Thanks for the help, guys. Both methods worked great.