Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
570 views
in Technique[技术] by (71.8m points)

swing - java comboBox autocomplete

Can someone tell me how to change this code to have autoselection and I could be able to write not existing items, because it doesnt let me to write new items.

public class ComboBoxFill extends PlainDocument
{
ComboBoxModel model;
JComboBox comboBox=new JComboBox();
JTextComponent editor;

public ComboBoxFill(ComboBoxModel model, JComboBox comboBox,JTextComponent editor) 
{
    this.model = model;
    this.comboBox=comboBox;
    this.editor=editor;
}
    public void insertString (int offs,String str,AttributeSet a) throws BadLocationException
    {
        String currentText=getText(0,getLength());
        String beforeOffset=currentText.substring(0,offs);
        String afterOffset=currentText.substring(offs,currentText.length());
        String futureText = beforeOffset+str+afterOffset;

    Object item =lookupItem(futureText);
    if (item!=null)
    {
        comboBox.setSelectedItem(item);
    }else 
    {
        item = comboBox.getSelectedItem();
        offs=offs-str.length();
        comboBox.getToolkit().beep();
    }

    super.remove(0, getLength());
    super.insertString(0, item.toString(), a);

    if (item.toString().equals(str)&&offs==0)
    {
        highlightCompletedText(0);
    }else{
        highlightCompletedText(offs+str.length());
        comboBox.setPopupVisible(true);
    }
}
private boolean startsWithIgnoreCase(String str1, String str2) {
    return str1.toUpperCase().startsWith(str2.toUpperCase());
}
private void highlightCompletedText(int start)
{
    editor.setCaretPosition (getLength());
    editor.moveCaretPosition(start);
}

private Object lookupItem(String pattern) 
{
    Object selectedItem=model.getSelectedItem();
if (selectedItem!=null && startsWithIgnoreCase(selectedItem.toString(), pattern)){
    return selectedItem;
}else{
    for (int i=0, n=model.getSize();i<n;i++){
        Object currentItem = model.getElementAt(i);
        if (startsWithIgnoreCase(currentItem.toString(),pattern))
        {
            return currentItem;
        }
    }
}
    return null;

}

}

I call it this way:

        JTextComponent editor3 = (JTextComponent) comboBox_2.getEditor().getEditorComponent();
    editor3.setDocument(new ComboBoxFill(comboBox_2.getModel(),comboBox_2, editor3));
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Java2s has an example for this: AutocompleteComboBox


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...