使用JComboBox作为搜索框 [英] Using JComboBox as a search box

查看:106
本文介绍了使用JComboBox作为搜索框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 JComboBox 从sql数据库中搜索查询。这是我的代码。

Im using a JComboBox to search a query from a sql database. Here is my code.

private void srKeyTyped(java.awt.event.KeyEvent evt){
    sr.removeAllItems();
    String sch = ((JTextField)sr.getEditor().getEditorComponent()).getText();
    String schh = "SELECT * FROM tbl WHERE name LIKE '" + sch + "%';";
    search = conn.getQuery(schh);
    try {
        while (search.next()) {
            String item = search.getString("name");
            sr.addItem(item);
        }
    } catch (SQLException ex) {
        Logger.getLogger(dataprocess.class.getName()).log(Level.SEVERE, null, ex);
    }
    sr.setSelectedItem(null);
    sr.setPopupVisible(true);

    System.out.println(sch);
}

sr = JComboBox

sr = JComboBox

但是当我在组合框中键入一个字母时,它会添加数据库中的所有项目。我开始知道 System.out.println(sch); 总是给出一个空字符串。只要我输入一个字母,组合框的文本字段就会变空(我不能输入带有两个字母的单词)。如何解决这个问题?谢谢。

But when i type a letter in combobox, it adds all the items in database. I came to know that System.out.println(sch); always gives an empty string. And as soon as i type a letter, the text field of combo box becomes empty(i cant type a word with two letters). How to fix this? Thank you.

推荐答案

您遇到问题的原因如下:

The reasons for your problems are the following:


  1. sch 始终为空是因为您正在调用 sr.removeAllItems(); 在调用字符串sch =((JTextField)sr.getEditor()。getEditorComponent())。getText(); 之前。这意味着在获得所选内容之前, JComboBox 的内容将被清除(连同选择)。

  1. sch is always empty is because you are calling sr.removeAllItems(); before you call String sch = ((JTextField)sr.getEditor().getEditorComponent()).getText();. This means that the contents of the JComboBox is cleared (along with the selection) before you get what is selected.

解决方案:调用 sr.removeAllItems(); 获得所选项目后。

Solution: Call sr.removeAllItems();AFTER you have got the selected item.

组合框变为空,因为您在重新填充后最后调用 sr.setSelectedItem(null);

The combo box becomes empty because you call sr.setSelectedItem(null); at the end after you have repopulated it.

解决方案:如果您想要输入的文本,那么 sr.getEditor()。setItem(scr);

Solution: If you want the entered text then sr.getEditor().setItem(scr);

仅限和想法,但尝试将方法的内容包含在 if语句中,并检查按下确认键。这样,方法内容将仅在输入所需字符串后执行,而不是每次按下键时执行。

Only and idea but try to enclose the contents of the method in an if statement and check if the Enter key is pressed. That way the method contents will only execute after the desired string is input and not EVERY time a key is pressed.

这篇关于使用JComboBox作为搜索框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆