2

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 ?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
HpTerm
  • 8,151
  • 12
  • 51
  • 67
  • +1 for asking a question, that helped me learn something new directly or indirectly, I just learned. hehe :-) – nIcE cOw Feb 23 '12 at 10:26

1 Answers1

2

I think that your implementations for Document going correct direction +1, you have to add AttributeSet and Caret as parameters

please look how AutoComplete JComboBox/JTextField works

Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319