在键入时从jcombobox获取文本

时间:2013-11-08 03:30:24

标签: java mysql

目前我已经解决了这个问题,它是使用一个文本字段和一个组合框,但这是非常不整洁,并希望删除文本字段,因为这是将数据输入到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);
     }
  }  
 }

1 个答案:

答案 0 :(得分:0)

不要使用KeyListener。

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

请参阅JComboBox的getEditor()方法。获得ComboBoxEditor后,您可以获得编辑器组件,默认情况下是JTextField。然后将DocumentListener添加到文本字段中。

阅读How to Write a Document Listener上的Swing教程中的部分以获取更多信息。