Using JComboBox as a search box

前端 未结 3 1769
一生所求
一生所求 2020-12-22 11:47

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.remove         


        
相关标签:
3条回答
  • 2020-12-22 11:53

    Use an ActionListener instead of the looking for the key press. When a combobox's selection is edited it will fire an ActionEvent when the editing is done.

    When you get this part working, you should move this logic off to another thread and populate the combobox's items when it returns. Otherwise your UI will hang while the SQL query occurs.

    0 讨论(0)
  • 2020-12-22 12:15

    The reasons for your problems are the following:

    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.

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

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

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

    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.

    0 讨论(0)
  • 2020-12-22 12:15

    Got the solution. This code works fine.

      private void srKeyTyped(java.awt.event.KeyEvent evt){
    
        String sch = ((JTextField)sr.getEditor().getEditorComponent()).getText();
        String schh = "SELECT * FROM tbl WHERE name LIKE '" + sch + "%';";
        search = conn.getQuery(schh);
        sr.removeAllItems();
        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);
        }
        System.out.println(sch);
        sr.setSelectedItem(null);
        sr.setPopupVisible(true);
        ((JTextField)sr.getEditor().getEditorComponent()).setText(sch);
      }
    

    Thanks to Skepi,Kleopatra, Guillaume Polet

    0 讨论(0)
提交回复
热议问题