O'Reilly logo

Swing Hacks by Chris Adamson, Joshua Marinacci

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required