Java Reference
In-Depth Information
The
public Class getColumnClass(int column)
method of the
TableModel
returns the class
type for a column in the data model. If the
JTable
class has a special renderer installed for that
particular class, it will use it to display that class. By default, the
AbstractTableModel
(and
DefaultTableModel
) implementations of
TableModel
return
Object.class
for everything. The
AbstractTableModel
class doesn't try to be smart about guessing what's in a column. However,
if you know that a particular column of the data model will always be numbers, dates, or some
other class, you can have the data model return that class type. This allows the
JTable
to try to
be smarter and use a better renderer.
Table 18-5 shows the preinstalled renderers within the
JTable
. If you have a table full of
numbers or just one column of numbers, for example, you can override
getColumnClass()
to
return
Number.class
for the appropriate columns; your numbers will be right-justified instead
of left-justified. With dates, using the default renderer for the
Date
class produces better-looking,
localized output.
Table 18-5.
Default JTable Renderers
Class
Renderer
Description
Boolean
JCheckBox
Centered
Date
JLabel
Right-aligned; uses
DateFormat
for output
Double
JLabel
Right-aligned; uses
NumberFormat
for output
Float
JLabel
Right-aligned; uses
NumberFormat
for output
Icon
JLabel
Centered
ImageIcon
JLabel
Centered
Number
JLabel
Right-aligned
Object
JLabel
Left-aligned
Figure 18-10 shows how a table might look before and after enabling the renderers.
"EFORE
!FTER
Figure 18-10.
Before and after enabling the renderers
You can choose to hard-code the class names for columns or have the
getColumnClass()
method be generic and just call
getClass()
on an element in the column. Adding the following
code to an
AbstractTableModel
implementation would allow the
JTable
to use its default renderers.
This implementation assumes that all entries for a particular column are one class type.