
Add a Filter History #14
Chapter 2, Lists and Combos
|
63
HACK
H A C K
#14
Add a Filter History
Hack #14
Remember previous searches and research with one click.
Chances are good that if you’ve searched for something once, it’s important
enough that you might well search for it again. In Apple’s Safari browser, a
search widget at the upper right has a little magnifying glass that remembers
your last 10 searches. Click the magnifying glass and a pop up appears with
the previous searches. Select one and it populates the field and does the
search immediately.
Here’s an implementation of the same idea, grafted onto the previous hack.
In other words, this remembers previous filters. It doesn’t remember every
keystroke—why bother remembering the searches “J” and “Jo” when you’re
really just interested in “Joe”—and only adds a search term to the filter
when the user presses return.
In the previous hack, you just needed to have a text field and a
JList. Now a
JButton needs to be attached to the text field, so the two are bundled
together in the inner class
FilterField. This class is responsible for:
• Telling the model to refilter on each keystroke in the
JTextField, as
before.
• Remembering the
JTextField’s contents as a saved search anytime the
Return or Enter key is pressed.
• Catching clicks on the
JButton and popping up a menu with previous
searches.
• Populating the
JTextField with a previous search when one is selected ...