
134
|
Chapter 3, Tables and Trees
#26 Search Through JTables Easily
HACK
Decorating the TableModel
Start by creating a class called TableSearcher that implements TableModel.
Next, create a simple decorator (or wrapper) that implements all of the
TableModel
methods and forwards the calls to the inner model. Depending
on your IDE, you may be able to automate the process (IntelliJ IDEA does it
for me). You’ll have to modify a few of the methods, but most are going to
remain unchanged. You don’t have to touch the
getColumnName( ) and
getColumnClass( ) methods, for example. Just forward them to the inner
TableModel:
public String getColumnName(int column) {
return tableModel.getColumnName(column);
}
public Class getColumnClass(int column) {
return tableModel.getColumnClass(column);
}
The getColumnCount( ) method is slightly different in that you have to check
if the
TableModel is null. This is because the table calls getColumnCount( )
first and calls other column methods only if there are valid columns. Here is
the code with the
null check:
public int getColumnCount( ) {
return (tableModel == null) ? 0 : tableModel.getColumnCount( );
}
Creating Logical Links to the Inner Table Model
Now, you need to introduce the idea of links between the inner table model
and this table model. Create a
Collection called rowToModelIndex. In it,
you’ll store
Integers corresponding to the inner table model row number, at
the index