
58
Chapter 2
C H A P T E R T W O
Lists and Combos
Hacks 13–20
Lists are underrated and underappreciated, and developers who don’t
appreciate JLists often use JTables when they don’t need to. But lists seem
to be making a comeback in desktop applications, and with good reason. A
lot of the data we deal with are single-dimension collections—search results,
recent URLs, downloaded files, etc.—and by making the onscreen version of
them more appealing and more usable, a list is the right way to present this
data to the user.
H A C K
#13
Filter JLists Hack #13
Make your 1,000-item list a lot more manageable.
One of the nicest things you can do with a large list is to make it manage-
able with a filter box. This is a text area that, as you type into it, removes list
elements so that only those that contain the typed text are visible.
The hack to do this basically involves having a list model with two represen-
tations of its contents: everything that is in the list, and a subset with just the
items to be displayed (i.e., those from the first list that match the filter). The
model’s
get methods are then rewired to use only the second list.
The implementation in this hack,
FilteredJList, is a single class with two
inner subclasses:
FilterModel and FilterField. The list owns the field, so a
caller can create the
JList fairly typically and then just ask for the field and
add it wherever it makes sense in the layout. ...