Search Through JTables Easily #26
Chapter 3, Tables and Trees
|
137
HACK
Recreating the inner table model links. Start by clearing the row-to-model
index to get rid of the previous results:
rowToModelIndex.clear( );
The
Hits
object contains a number of
Documents
, just like the ones you put
into the index. Remember, you put a field in each
Document
with the name
ROW_NUMBER. So, now you can iterate through the Documents and get the row
number from the field value:
for (int t=0; t<hits.length( ); t++){
Document document = hits.doc(t);
Field field = document.getField(ROW_NUMBER);
Integer rowNumber = new Integer(field.stringValue( ));
}
The last step is to add an Integer to the row-to-model index with the row
number retrieved from the document. Then, tie up all the loose ends by fir-
ing a table model update.
Try It Out
Because you’re creating this table model as a decorator, it’s extremely easy
to use. The normal code to set up a
JTable and a custom table model
MyTableModel looks like this:
JTable table = new JTable( );
MyTableModel myTableModel = new MyTableModel( );
table.setTableModel(myTableModel);
All you need to do is wrap the MyTableModel with a TableSearcher and set the
table model for the
JTable as the TableSearcher:
JTable table = new JTable( );
MyTableModel myTableModel = new MyTableModel( );
TableSearcher tableSearcher = new TableSearcher(myTableModel);
table.setTableModel(tableSearcher);
Then, you just need to call the search method at the appropriate time. Usu-
ally, you’ll have a search field to enter the search and a search button to start
the search, so just attach an action listener to them both to fire off a search:
final JTextField searchField = new JTextField( );
JButton searchButton = new JButton("Go");
ActionListener searchListener = new ActionListener( ) {
public void actionPerformed(ActionEvent e) {
searchTableModel.search(searchField.getText().trim().toLowerCase( ));
searchField.requestFocus( );
}
};

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.