Java Reference
In-Depth Information
Tip
The preceding
DVDTableModel
has the capability to convert DVD model objects one at a time, but
sometimes it is more convenient to provide a method that will convert entire collections of model objects.
That way, a search method could use a single call to convert its entire set of search results.
■
Using the TableModel with a JTable
Once a
TableModel
has been implemented, using it with a
JTable
is a simple task. A
TableModel
may be specified in the constructor of a
JTable
object. For example, the following snippet will
create a new
JTable
using the
DVDTableModel
that was described in the previous section:
JTable table = new JTable (new DVDTableModel ());
The preceding statement will create a
JTable
using a
DVDTableModel
, but the table display
will be empty, since no data is contained in the specified
DVDTableModel
instance.
■
Note
A
JTable
instance can have its internal table model modified after it is instantiated. The
setModel
method updates a
JTable
's internal
TableModel
member and therefore updates the data the
JTable
displays. Data can also be added to a
JTable
's
TableModel
reference by calling the method
getModel
method on a
JTable
instance. In our case, this method can be called to get a reference to the
JTable
's
internal
DVDTableModel
reference. Then the method
addRecord
can be called to add a row to a
JTable
.
Because alterations to a
JTable
's
TableModel
translates into an updated View, the client
must be set up to take advantage of this schema. The
MainWindow
class contains the private
member
private DVDTableModel tableData;
This data member will always hold the main
JTable
's
TableModel
. Because all data trans-
fer between the View and the Controller is done via a
DVDTableModel
object, this member is
always updated to reflect changes to the database's state.
Once the database has been updated or queried, the resulting table model is placed into
the
tableData
member. After calling the Controller, the
MainWindow
class calls its internal pri-
vate method
setupTable
. This method contains the statements in Listing 8-17.
Listing 8-17.
The setupTable Method
private void setupTable() {
// Preserve the previous selection
int index = mainTable.getSelectedRow();
String prevSelected = (index >= 0)
? (String) mainTable.getValueAt(index, 0)
: "";