
270
|
Chapter 7, Text
#50 Auto-Completing Text Fields
HACK
You can hide the window at this point and look at the selection value. Since
the
Completer just puts Strings in the list model, you can pull out the
selected value and set that as the text of the field. And you’re done.
Well, not quite. If you call
setText( )
directly in
valueChanged( )
, you’ll be
thrown an
IllegalStateException
. The problem is that you’re attempting to
change the value of the
Document
while it’s already being changed. In other
words, firing off the
DocumentEvent is part of the document edit that began
with the user’s keystroke that led to the completion menu appearing; this
edit needs to complete before another is attempted. As you can see in this
hack, the workaround is to create a worker thread to set the field with the
clicked text, and to invoke that worker on a later cycle through the event
loop. This arrangement returns immediately and lets the first edit finish,
then sets the field later.
Test Out Auto-Complete
To test this class, you need to put the CompletableJTextField in a GUI and
provide a way to give it some completions. The
TestCompletableJTextField
class in Example 7-5 does just that, offering a second JTextField where you
can enter strings that will be offered as completions to text typed into the
CompletableJTextField. When run, the test GUI originally looks like
Figure 7-3.
Example 7-5. A GUI to exercise the CompletableJTextField ...