Searching around for single line auto-completion I have found code here and there and finally ended up using this one
public class AutoCompleteDocument extends PlainDocument {
private final List<String> dictionary = new ArrayList<String>();
private final JTextComponent jTextField;
public AutoCompleteDocument(JTextComponent field, String[] aDictionary) {
jTextField = field;
dictionary.addAll(Arrays.asList(aDictionary));
}
@Override
public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException {
super.insertString(offs, str, a);
String word = autoComplete(getText(0, getLength()));
if (word != null) {
super.insertString(offs + str.length(), word, a);
jTextField.setCaretPosition(offs + str.length());
jTextField.moveCaretPosition(getLength());
}
}
public String autoComplete(String text) {
for (Iterator<String> i = dictionary.iterator(); i.hasNext();) {
String word = i.next();
if (word.startsWith(text)) {
return word.substring(text.length());
}
}
return null;
}
}
Then I use this like
autoCompleteDoc = new AutoCompleteDocument(myTextField,myDictionary);
myTextField.setDocument(autoCompleteDoc);
Everything works fine.
My problem is the following :
The myTextField has a listener for actionPerformed so that when I press enter key it does some processing.
Unfortunately what I would like is when the text is "proposed" (highlighted), when I press enter it validates the proposition so I can continue typing and only when no text is proposed (no highlight) then when I press enter it does my processing.
I'm simply stuck with no idea where to start from. Anyone can help me out ?