0

目前我有一个解决这个问题的方法是使用一个文本字段和一个组合框,但是这非常不整洁,希望删除文本字段,因为这是将数据输入到 mysql 数据库并检索它,所以我需要能够将结果添加到组合框中,因为它在文本字段中

 private void jTextField15KeyReleased(java.awt.event.KeyEvent evt) {                                         
     String ThePub = jTextField15.getText();
      int publengh = ThePub.length();
       if (publengh > 2) {
         jTextField15.setVisible(false);
         fillpub(ThePub);
                       }  
  public void fillpub(String pub) {
    Connection con;
     ResultSet rs;
     PreparedStatement pst;
     String thedata;
     try {
         String cs = "jdbc:mysql://localhost:3306/booksalvation4";
         String user = "root";
         String password = "letmein";
         pub = "'" + pub + "%'";
          con = DriverManager.getConnection(cs, user, password);
           String query = "select * from publisher where name like" + pub;
                pst = con.prepareStatement(query);
                 rs = pst.executeQuery();
         while (rs.next()) {
               thedata = rs.getString(2);
             jComboBox11.addItem(thedata);
         }
     } catch (SQLException ex) {
         Logger.getLogger(mainJFrame.class.getName()).log(Level.SEVERE, null, ex);
     }
  }  
 }
4

1 回答 1

0

不要使用 KeyListener。

相反,您应该使用DocumentListener. 您可以将 DocumentListener 添加到用作 JComboBox 编辑器的文本字段的 Document 中。

参见getEditor()JComboBox 的方法。一旦你有了,ComboBoxEditor你就可以得到默认情况下是一个 JTextField 的编辑器组件。然后将 DocumentListener 添加到文本字段。

阅读 Swing 教程中有关如何编写文档侦听器的部分以获取更多信息。

于 2013-11-08T04:09:47.650 回答