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 that corresponds to this table model’s row. So, if the fifth row in
the inner model is the first row in this model, you would store an
Integer
value of 5 as the first in the rowtoModelIndex.
This method clears the searching state by making a one-to-one mapping of
the inner table model to this table model:
private void clearSearchingState( ){
searchString = null;
rowToModelIndex.clear( );
for (int t=0; t<tableModel.getRowCount( ); t++){
rowToModelIndex.add(new Integer(t));
}
}
Now, you need to change the row reference methods to indirect through the
row to model index before hitting the inner table model:

Get Swing Hacks now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.