138
|
Chapter 3, Tables and Trees
#26 Search Through JTables Easily
HACK
searchButton.addActionListener(searchListener);
searchField.addActionListener(searchListener);
Finishing Touches
You’ve got the bare bones down, but there are a few things you’ll want to
add to make everything a little more functional. Here are a couple of ideas.
Listen to inner table updates. If the inner table model changes, you need to
know about it. Otherwise, your search results will not jive with the inner
table model. The simple solution is to add a
TableModelListener to the inner
table to rebuild the index, and then rerun the search against the new index.
Here’s the code:
private class TableModelHandler implements TableModelListener {
public void tableChanged(TableModelEvent e) {
// If we're not searching, just pass the event along.
if (!isSearching( )) {
clearSearchingState( );
reindex( );
fireTableChanged(e);
return;
}
// Something has happened to the data that may
// have invalidated the search.
reindex( );
search(searchString);
fireTableDataChanged( );
}
}
You should consider extending this hack if you have serious performance
considerations. You could narrow down the area of the table that changed
to fire more accurate events to the table.
Clear search results for blank search. When users search with an empty
string, they typically expect that to clear the search. The easiest way to do
this is to check for an empty string in the search method. If they search with
an empty string, clear the search and rerun the method that indexes all of
the inner table model without a search:
public void search(String searchString){
if (searchString == null || searchString.equals("")){
clearSearchingState( );
fireTableDataChanged( );
return;
}
//rest of search method
}

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.