2

単一行のオートコンプリートを検索すると、あちこちでコードが見つかり、最終的にこれを使用することになりました

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;
    }  
}

次に、これを次のように使用します

autoCompleteDoc = new AutoCompleteDocument(myTextField,myDictionary);
myTextField.setDocument(autoCompleteDoc);

すべて正常に動作します。

私の問題は次のとおりです。

myTextField には actionPerformed のリスナーがあり、Enter キーを押すと何らかの処理が行われます。

残念ながら、私が望むのは、テキストが「提案された」(強調表示された) ときです。Enter キーを押すと提案が検証されるので、入力を続けることができます。 .

私はどこから始めればいいのかわからないだけで立ち往生しています。誰でも私を助けることができますか?

4

1 に答える 1

2

Document正しい方向に+1するための実装ではAttributeSetCaretパラメータとして追加する必要があると思います

AutoComplete JComboBox/JTextFieldがどのように機能するかを見てください

于 2012-02-23T09:59:20.033 に答える