106
|
Chapter 3, Tables and Trees
#21 Size Your Columns to Suit Your JTable’s Contents
HACK
Accounting for Header Cells
There’s a problem with the new weighting of the column widths: since the
one-digit contents of the count column are so narrow, the count column
header has been crushed to the point where Swing needs to show it with
ellipses. Not so good.
The problem, of course, is that the width of the header was never consid-
ered in the preferred width calculation. You can do that yourself by chang-
ing the logic to prefer the wider of the widest content cell and the header
cell. This means you need to get the header cell renderer (either from the
TableColumn or the JTableHeader), then render a cell and get its width.
To do this, replace these two lines:
TableColumn column = columnModel.getColumn (col);
column.setPreferredWidth (maxwidth);
with these:
TableColumn column = columnModel.getColumn (col);
TableCellRenderer headerRenderer = column.getHeaderRenderer( );
if (headerRenderer == null)
headerRenderer = table.getTableHeader().getDefaultRenderer( );
Object headerValue = column.getHeaderValue( );
Component headerComp =
headerRenderer.getTableCellRendererComponent (table,
headerValue,
false,
false,
0,
col);
maxwidth = Math.max (maxwidth,
headerComp.getPreferredSize( ).width);
column.setPreferredWidth (maxwidth);
Figure 3-2. JTable columns resized to suit their contents

Get Swing Hacks now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.