
266
|
Chapter 7, Text
#50 Auto-Completing Text Fields
HACK
The text field that pops up a window of recently viewed sites is a happy
compromise. It jogs your memory by showing you completion options, and
it saves lots of typing by letting you simply click one of the options and hav-
ing that text inserted immediately into the text field.
A Self-Completing Text Field
This hack takes a JTextField and has it manage a JWindow, which contains a
JList of possible completion values. The real work is done by an inner class
that manages the list of completions and has a
javax.util.regex.Pattern
object to match each potential completion against the field’s current text.
Example 7-4 is what you need to get going.
Example 7-4. A JTextField that manages a pop-up list of completions
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import java.util.*;
import java.util.regex.*;
public class CompletableJTextField extends JTextField
implements ListSelectionListener {
Completer completer;
JList completionList;
DefaultListModel completionListModel;
JScrollPane listScroller;
JWindow listWindow;
public CompletableJTextField (int col) {
super (col);
completer = new Completer( );
completionListModel = new DefaultListModel( );
completionList = new JList(completionListModel);
completionList.setSelectionMode (ListSelectionModel.SINGLE_SELECTION);
completionList.addListSelectionListener ...