Java Reference
In-Depth Information
getRowCount()
has to be implemented to return the number of rows in the table.
getColCount()
has to be implemented to return the number of columns in the
table.
getValueAt(r,c)
has to be implemented to return the content of the table cell
in column
c
of row
r
.
Besides these three abstract methods
AbstractTableModel
contains some non-
abstract methods one would often like to override:
String getColumnName(
int
c)
Class getColumnClass(
int
c)
boolean
isCellEditable(
int
r,
int
c)
void
setValueAt(Object val,
int
r,
int
c)
getColumnName(c)
returns the name of column
c
as a string. By default, an
Ab-
stractTableModel
assigns the names
A
to the
columns. Overriding
getColumnName
by your own implementation allows you
to specify other names.
,
B
,
C
,...,
Z
,
AA
,
AB
,
AC
,...
getColumnClass(c)
returns the class of the objects in column
c
.Bydefault, an
AbstractTableModel
returns class
Object
. One should override
getColumn-
Class(c)
to return the correct class of the objects in column
c
. This way one
ensures that the correct renderer is used to display the entries. As mentioned
above, tables are column-oriented and in every column the objects should be
of the same class. To determine the appropriate class for column
c
one can
look at the entry in the first row:
getValueAt(0,c).getClass()
.
isCellEditable(r, c)
the return value is
true
if the cell is editable and
false
otherwise. The default implementation returns
false
, i.e. the user cannot
change the content of the cell. The programmer can override this method
to make some cells editable by the user.
setValueAt(Object val, r, c)
can be used to set the value of the cell in row
r
and column
c
to
val
. The default implementation has an empty body, i.e.
it does not change the value of the cell. The programmer can override this
method to change the values of editable cells.
In the following listing we provide an implementation of
MultiplicationTable-
Model
. The numbers of rows and columns are given as an argument in the con-
structor. Method
getValueAt(r,c)
is implemented to return the product of
r
and
c
. Method
getColumnName(c)
is overridden to return the string
Col
followed
by the number
c
as a string. In Figure 16.4 the results are shown when using
automatic resizing of the column width and without using it.
We also list the class
MultiplicationTableFrame
. Such a frame generates a
MultiplicationTableModel
and a
JTable
using this model. The table is embed-
ded into a scroll pane which in turn is embedded into the frame.
Search WWH ::
Custom Search