java 组合框自动完成

标签 java swing autocomplete jcombobox

有人可以告诉我如何更改此代码以进行自动选择,并且我可以编写不存在的项目,因为它不允许我编写新项目。

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;

}

}

我这样调用它:

        JTextComponent editor3 = (JTextComponent) comboBox_2.getEditor().getEditorComponent();
    editor3.setDocument(new ComboBoxFill(comboBox_2.getModel(),comboBox_2, editor3));

最佳答案

Java2s 有一个示例:AutocompleteComboBox

关于java 组合框自动完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6777473/

相关文章:

java - 试图在android中的两个 Activity 之间传递长数组

java - 在 Java 中处理键盘键 ALT+F4 组合

autocomplete - Android Studio - 自动标记关闭 - 以新行关闭

javascript - Google Places Autocomplete place_changed 事件在表单提交后按回车键触发

ArrayList 上的 JAVA SimpleDateFormat 更改日期

java - 未找到 Java 类型的消息正文编写器 mime 类型 application/x-www-form-urlencoded

java - 使用递归而不是循环打印嵌套数组中的元素

java - jcombobox 与 jbutton 一起使用

java - 第二次单击鼠标时 JPanel 不更新

javascript - 如何将谷歌自动完成结果仅限于城市和国家