0

在Jcombobox中,当我输入一些字母说('j')时,默认情况下会聚焦第一个以'j'开头的项目。但是相同的逻辑不适用于许多字母(比如'ji')。如何制作可能以这样的方式,当我输入“ji”时,它应该专注于以“ji”开头的第一个项目等等?

4

3 回答 3

1

在Jcombobox中,当我输入一些字母说('j')时,默认情况下会聚焦第一个以'j'开头的项目。但是相同的逻辑不适用于许多字母(比如'ji')。如何制作可能的方式是,当我键入“ji”时,它应该专注于以“ji”开头的第一个项目,依此类推。

请参阅自动完成 JComboBox / JTextField

于 2013-05-24T08:46:23.723 回答
0

我不喜欢发布大的东西,但这是我多年前使用的源代码(不记得在哪里)并修复了一些问题以使其正常工作。

用法 :

String[] aItems = new String[] {"Ester", "Jordi", "Jordina", "Jorge", "Sergi"};

JAutoCompleteComboBox cboxInputModelNumber = new JAutoCompleteComboBox();

for(nItem = 0;nItem < lItems.size();nItem++)
{
    aItems[nItem] = lItems.get(nItem).getNumber();
}

cboxInputModelNumber.getCompleter().setItems(lItems.toArray());

JAutoCompleteComboBox.java

import java.util.List;
import java.util.Vector;
import javax.swing.ComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JTextField;

/**
 *
 * @author Improved by Alexandre Lavoie
 * 
 * Source : http://www.java2s.com/Code/Java/Swing-Components/AutocompleteComboBox.htm
 */
public class JAutoCompleteComboBox extends JComboBox
{
    private AutoCompleter completer;

    public JAutoCompleteComboBox()
    {
        super();
        addCompleter();
    }

    public JAutoCompleteComboBox(ComboBoxModel cm)
    {
        super(cm);
        addCompleter();
    }

    public JAutoCompleteComboBox(Object[] items)
    {
        super(items);
        addCompleter();
    }

    public JAutoCompleteComboBox(List v)
    {
        super((Vector) v);
        addCompleter();
    }

    private void addCompleter()
    {
        setEditable(true);
        completer = new AutoCompleter(this);
    }

    public void autoComplete(String str)
    {
        this.completer.autoComplete(str,str.length());
    }

    public String getText()
    {
        return ((JTextField) getEditor().getEditorComponent()).getText();
    }

    public void setText(String text)
    {
        ((JTextField) getEditor().getEditorComponent()).setText(text);
    }

    public boolean containsItem(String itemString)
    {
        for(int i = 0; i < this.getModel().getSize(); i++)
        {
            String _item = "" + this.getModel().getElementAt(i);

            if(_item.equals(itemString))
            {
                return true;
            }
        }

        return false;
    }

    public AutoCompleter getCompleter()
    {
        return completer;
    }
}

自动完成程序.java

import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.List;
import java.util.Vector;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JTextField;

/**
 *
 * @author Improved by Alexandre Lavoie
 * 
 * Source : http://jwms-lqik2004.googlecode.com/svn/jwms_linux_eclipse/src/com/res0w/jwms/method/AutoCompleter.java
 */
public class AutoCompleter implements KeyListener, ItemListener
{
    private JComboBox m_oParent = null;
    private JTextField m_oEditor = null;
    private ComboBoxModel m_oModel = null;
    private Object[] items;

    public AutoCompleter(JComboBox comboBox)
    {
        m_oParent = comboBox;
        m_oEditor = (JTextField) comboBox.getEditor().getEditorComponent();
        m_oEditor.addKeyListener(this);
        m_oModel = comboBox.getModel();
        m_oParent.addItemListener(this);
    }

    public void keyTyped(KeyEvent e)
    {

    }

    public void keyPressed(KeyEvent e)
    {

    }

    public void keyReleased(KeyEvent e)
    {
        char ch = e.getKeyChar();

        // TODO : Maybe catch keys that won't update the content here
        {
            int caretPosition = m_oEditor.getCaretPosition();
            String str = m_oEditor.getText();

            if(str.length() == 0)
            {
                m_oParent.setPopupVisible(false);
                return;
            }
            else
            {
                autoComplete(str,caretPosition);
            }
        }
    }

    /**
    *   ×Ô¶¯Íê³É¡£¸ù¾ÝÊäÈëµÄÄÚÈÝ£¬ÔÚÁбíÖÐÕÒµ½ÏàËƵÄÏîÄ¿.
    */
    protected void autoComplete(String strf, int caretPosition)
    {
        Object[] opts;
        opts = getMatchingOptions(strf.substring(0,caretPosition));

        if(m_oParent != null)
        {
            m_oModel = new DefaultComboBoxModel(opts);
            m_oParent.setModel(m_oModel);
        }

        if(opts.length > 0)
        {
            m_oEditor.setCaretPosition(caretPosition);
            m_oEditor.setText(strf.substring(0,caretPosition));

            if(m_oParent != null)
            {
                try
                {
                    m_oParent.showPopup();
                }
                catch(Exception ex)
                {
                    ex.printStackTrace();
                }
            }
        }
        else
        {
            m_oEditor.setText(strf);
        }
    }

    /**
    *
    *   ÕÒµ½ÏàËƵÄÏîÄ¿,   ²¢ÇÒ½«Ö®ÅÅÁе½Êý×éµÄ×îÇ°Ãæ¡£
    *   @param   str
    *   @return   ·µ»ØËùÓÐÏîÄ¿µÄÁÐ±í¡£
    */
    protected Object[] getMatchingOptions(String str)
    {
        List v = new Vector();

        for(int k = 0; k < items.length; k++)
        {
            Object itemObj = items[k];

            if(itemObj != null)
            {
                String item = itemObj.toString();
                if(KMPAlgorithm.kmp(item,str))
                {
                    v.add(items[k]);
                }
            }
        }
        return v.toArray();
    }

    protected Object[] getMatchingOptionsDel(String str)
    {
        List v = new Vector();

        for(int k = 0; k < items.length; k++)
        {
            Object itemObj = items[k];

            if(itemObj != null)
            {
                String item = itemObj.toString().toLowerCase();

                if(KMPAlgorithm.kmp(item, str))
                {
                    v.add(items[k]);
                }
            }
        }

        return v.toArray();
    }

    public void itemStateChanged(ItemEvent event)
    {
        if (event.getStateChange() == ItemEvent.SELECTED)
        {
            int caretPosition = m_oEditor.getCaretPosition();

            if(caretPosition != -1)
            {
                try
                {
                    m_oEditor.moveCaretPosition(caretPosition);
                }
                catch(IllegalArgumentException ex)
                {
                    ex.printStackTrace();
                }
            }
        }
    }

    public void setItems(Object[] x)
    {
        items = x;
    }
}

KMPAlgorithm.java

/**
 *
 * @author Alexandre Lavoie
 * 
 * Source : http://jwms-lqik2004.googlecode.com/svn/jwms_linux_eclipse/src/com/res0w/jwms/method/KMPAlgorith.java
 */
public class KMPAlgorithm {

    public static boolean kmp(String target, String pattern) {
        /*int pLen = pattern.length();
        int tLen = target.length();
        //the fail function
        int failFunc[] = new int[pLen];
        failFunc[0] = -1;
        //build fail function
        for (int i = 1; i < pLen; i++) {
            int j = failFunc[i - 1];
            while (pattern.charAt(i) != pattern.charAt(j + 1) && j >= 0) {
                //recursion
                j = failFunc[j];
            }
            if (pattern.charAt(i) == pattern.charAt(j + 1)) {
                failFunc[i] = j + 1;
            } else {
                failFunc[i] = -1;
            }
        }
        int pPos = 0, tPos = 0;
        while (tPos < tLen && pPos < pLen) {
            if (target.charAt(tPos) == pattern.charAt(pPos)) {
                //match ,then do forward
                tPos++;
                pPos++;
            } else if (pPos == 0) {
                //target go forward
                tPos++;
            } else {
                //target postion don't change,pattern go back
                pPos = failFunc[pPos - 1] + 1;
            }
        }
        if (pPos < pLen) {
            return false;
        } else {
            return true;
        }*/

        return target.toLowerCase().startsWith(pattern.toLowerCase());
    }
}
于 2013-05-24T08:44:50.823 回答
0

在子类 JComboBox 中实现 KeyListener 并搜索 JCombobox 元素。

于 2013-05-24T08:43:18.393 回答