来自查询的可扩展,可编辑,可搜索的JComboBox

时间:2016-01-26 13:05:06

标签: java mysql swing jcombobox

我需要一个可编辑的JComboBox,每当我在其中键入一个字母时,在数据库中搜索所有字符串,如编写的字符串,并且每当我使用查询的新结果键入字母时它也会自动扩展组合框。 / p>

我已经尝试了几个听众,但不能让它们正常工作,这就是我到目前为止所做的。

    private void jComboBox3ActionPerformed(java.awt.event.ActionEvent evt) {  
         try{
                String typedString = jComboBox3.getEditor().getItem().toString();

                jComboBox3.showPopup();

                DefaultComboBoxModel model = new DefaultComboBoxModel();
                System.out.println(typedString); 
                    try {
                        String query = "SELECT Client.Surname, Client.Sex, Client.CodeClient FROM Client WHERE Client.Surname LIKE '"+typedString+"%' ORDER BY Client.Surname;";
                        bd.getConn();
                        bd.statement=bd.conn.prepareStatement(query);
                        bd.rs=(ResultSet)bd.statement.executeQuery(query);
                        while(bd.rs.next()){
                            String client = bd.rs.getString("Client.Surname");
                            String sex = bd.rs.getString("Client.Sex");
                            String codClient = bd.rs.getString("Client.CodeClient");
                            switch(sex){
                                case "M":   model.addElement("Mr. "+bd.rs.getString("Client.Surname"));
                                            break;
                                case "F":   model.addElement("Ms. "+bd.rs.getString("Client.Surname"));
                                            break;
                                default:    model.addElement(bd.rs.getString("Client.Surname"));
                                            break;
                            }

                        }
                    } catch (SQLException ex) {
                        Logger.getLogger(Registro.class.getName()).log(Level.SEVERE, null, ex);
                    }

                    jComboBox3.setModel(model);
                    if (jComboBox3.getItemCount() > 0) {
                        jComboBox3.getEditor().setItem(typedString);
                        jComboBox3.showPopup();                     

                    } else {
                        jComboBox3.addItem(typedString);
                    }
            }catch   (IllegalComponentStateException e) {
                return;
            }
}

0 个答案:

没有答案