Java Reference
In-Depth Information
more flexible data display, a good table class would need additional methods and constructors
to fit within the paradigm of the MVC pattern. It so happens that the
JTable
fits incredibly well
into this pattern—so much so that the
JTable
actually defines its own model: the
TableModel
interface.
■
Note
Many Swing components, such as the
JTable
and the
JTree
, implement their own MVC
architecture.
The TableModel
The
TableModel
is one of the easiest and most flexible ways to display a data set in a
JTable
.
Earlier in this chapter, the interaction between the Model and the View in the MVC pattern
was discussed in detail. As you may recall, the View is solely responsible for taking the data
contained in a Model object and converting it into a visual representation. The
JTable
actually incorporates this part of the MVC pattern into its standard API. An implemented
TableModel
interface acts as the Model in this case, and the
JTable
instance acts as the View.
The
TableModel
is essentially handed off to a
JTable
instance, and the table widget renders
the data model into the visual representation. The Model may be specified in the
JTable
constructor:
JTable table = new JTable (TableModel model);
or set via the void
setTableModel (TableModel model)
instance method. Once the
TableModel
is passed to the table instance, the
JTable
class literally takes care of the rest.
At this point, the
JTable
may seem like a snap to use. While the
JTable
is quite easy to
use, the bulk of the work for the developer comes in the task of implementing the
TableModel
interface.
As with event listener interfaces, not all of the methods specified in the
TableModel
interface are always necessary for a given data set. For instance, if a developer wanted to
implement a simple
TableModel
, it would be inefficient to have to provide implementations
for all the interface methods, such as
removeTableModelListener(TableModelListener
modListener)
. Thus, an adapter class is provided that functions in a manner similar to
event adapter classes. The
AbstractTableModel
class implements the
TableModel
interface
such that each method already has a default implementation. Therefore, extending the
AbstractTableModel
class is usually the best starting point when creating a custom
TableModel
.
In version 2.0 of the Denny's DVDs application, the
DVDTableModel
class is an extension
of the
AbstractTableModel
class. The
DVDTableModel
does not need to implement the
getColumnClass
,
removeTableModelListener
, and
addTableModelListener
methods, so their
default implementations provided by the abstract implementation will suffice. All other
methods in the
TableModel
interface will be implemented.
First, notice the addition of the two member variables in the
DVDTableModel
class in
Listing 8-10.