2013-05-28 26 views
0

我想要的是一個可編輯的jcombobox。 當用戶鍵入它時,它應搜索數據庫並在數據庫中顯示用戶輸入的文本開頭的名稱。 例如。 :如果用戶輸入'a'。 然後jcombobox應顯示數據庫中以'a'開頭的所有名稱。帶有Autosuggest的文本字段

如果數據庫包含名稱aaron,aidan,kim。 當用戶鍵入「A」,則組合框應建議名稱亞倫和艾丹

/* 
    * To change this template, choose Tools | Templates 
    * and open the template in the editor. 
    */ 
    package Main; 

    /** 
    * 
    * @author John 
    */ 
    import javax.swing.event.*; 
    import java.awt.event.*; 
    import java.sql.Connection; 
    import java.sql.DriverManager; 
    import java.sql.ResultSet; 
    import java.sql.Statement; 
    import java.util.ArrayList; 
    import java.util.Vector; 
    import javax.swing.DefaultComboBoxModel; 
    import javax.swing.JOptionPane; 
    import javax.swing.MutableComboBoxModel; 
    import javax.swing.text.JTextComponent; 

    public class test extends javax.swing.JFrame { 

/** 
* Creates new form test 
*/ 
public test() { 


    initComponents(); 



((JTextComponent)  jComboBox1.getEditor().getEditorComponent()).getDocument().addDocumentListener(new DocumentListener() { 




     @Override 
     public void insertUpdate(DocumentEvent e) { 

      String tmp = jComboBox1.getEditor().getItem().toString(); 
      ArrayList<String> scripts = new ArrayList<String>(); 
      String str1=""; 
    try 
    { 





    String str="SELECT item FROM item WHERE item LIKE '"+tmp+"%'"; 

    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); 
    Connection con=DriverManager.getConnection("jdbc:odbc:ds1", "sa" , "creative"); 
    Statement stmt=con.createStatement(); 
    ResultSet rs=stmt.executeQuery(str); 
    while(rs.next()) 
    { 

     str1=rs.getString("item"); 
     scripts.add(str1); 
     jComboBox1.addItem(str1); 

    } 





    } 
    catch(Exception ex) 
    { 
    System.out.println("error"+ex); 
    } 

     } 

     @Override 
     public void removeUpdate(DocumentEvent e) { 
      String tmp = jComboBox1.getEditor().getItem().toString(); 

     } 

     @Override 
     public void changedUpdate(DocumentEvent e) { 

     } 


    }); 






} 




/** 
* This method is called from within the constructor to initialize the form. 
* WARNING: Do NOT modify this code. The content of this method is always 
* regenerated by the Form Editor. 
*/ 
@SuppressWarnings("unchecked") 
// <editor-fold defaultstate="collapsed" desc="Generated Code">       
private void initComponents() { 

    jComboBox1 = new javax.swing.JComboBox(); 

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); 

    jComboBox1.setEditable(true); 

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); 
    getContentPane().setLayout(layout); 
    layout.setHorizontalGroup(
     layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
     .addGroup(layout.createSequentialGroup() 
      .addGap(105, 105, 105) 
      .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 240, javax.swing.GroupLayout.PREFERRED_SIZE) 
      .addContainerGap(141, Short.MAX_VALUE)) 
    ); 
    layout.setVerticalGroup(
     layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
     .addGroup(layout.createSequentialGroup() 
      .addGap(86, 86, 86) 
      .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) 
      .addContainerGap(194, Short.MAX_VALUE)) 
    ); 

    pack(); 
}// </editor-fold>       

/** 
* @param args the command line arguments 
*/ 
public static void main(String args[]) { 
    /* Set the Nimbus look and feel */ 
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> 
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. 
    * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
    */ 
    try { 
     for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { 
      if ("Nimbus".equals(info.getName())) { 
       javax.swing.UIManager.setLookAndFeel(info.getClassName()); 
       break; 
      } 
     } 
    } catch (ClassNotFoundException ex) { 
     java.util.logging.Logger.getLogger(test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } catch (InstantiationException ex) { 
     java.util.logging.Logger.getLogger(test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } catch (IllegalAccessException ex) { 
     java.util.logging.Logger.getLogger(test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } catch (javax.swing.UnsupportedLookAndFeelException ex) { 
     java.util.logging.Logger.getLogger(test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } 
    //</editor-fold> 

    /* Create and display the form */ 
    java.awt.EventQueue.invokeLater(new Runnable() { 
     public void run() { 
      new test().setVisible(true); 
     } 
    }); 
} 
// Variables declaration - do not modify      
private javax.swing.JComboBox jComboBox1; 
// End of variables declaration     


} 

當我在與由JComboBox中顯示鍵入的字母開頭的數據庫運行此,只有第一個名字。出現以下錯誤 errorjava.lang.IllegalStateException:嘗試在通知中發生變異

+0

可以說,我會看看SwingLabs,SwingX庫的'AutoCompleteDecorator' – MadProgrammer

回答

0

自動建議類型可編輯Jcombo Box - 根據您鍵入的內容顯示來自數據庫的建議。

/* 
* To change this template, choose Tools | Templates 
* and open the template in the editor. 
*/ 
package Main; 

import java.awt.event.KeyAdapter; 
import java.awt.event.KeyEvent; 
import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.ResultSet; 
import java.sql.Statement; 
import java.util.ArrayList; 
import java.util.List; 
import javax.swing.DefaultComboBoxModel; 
import javax.swing.JComboBox; 
import javax.swing.JTextField; 
import javax.swing.SwingUtilities; 

/** 
* 
* @author John 
*/ 
public class test2 extends javax.swing.JFrame { 

/** 
* Creates new form test2 
*/ 
public test2() { 
    initComponents(); 

    final JTextField textfield = (JTextField)  jComboBox1.getEditor().getEditorComponent(); 
    textfield.addKeyListener(new KeyAdapter() { 
     public void keyReleased(KeyEvent ke) { 
      SwingUtilities.invokeLater(new Runnable() { 
       public void run() { 
        comboFilter(textfield.getText()); 
       } 
      }); 
     } 
    }); 
} 



public void comboFilter(String enteredText) { 
    List<String> filterArray= new ArrayList<String>(); 

      String str1=""; 

    try 
    { 


    String str="SELECT item FROM item WHERE item LIKE '"+enteredText+"%'"; 

    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); 
    Connection con=DriverManager.getConnection("jdbc:odbc:ds1", "sa" , "creative"); 
    Statement stmt=con.createStatement(); 
    ResultSet rs=stmt.executeQuery(str); 
    while(rs.next()) 
    { 

     str1=rs.getString("item"); 
     filterArray.add(str1); 


    } 

    } 
    catch(Exception ex) 
    { 
    System.out.println("error"+ex); 
    } 




    if (filterArray.size() > 0) { 
     jComboBox1.setModel(new DefaultComboBoxModel(filterArray.toArray())); 
     jComboBox1.setSelectedItem(enteredText); 
     jComboBox1.showPopup(); 
    } 
    else { 
     jComboBox1.hidePopup(); 
    } 
} 

/** 
* This method is called from within the constructor to initialize the form. 
* WARNING: Do NOT modify this code. The content of this method is always 
* regenerated by the Form Editor. 
*/ 
@SuppressWarnings("unchecked") 
// <editor-fold defaultstate="collapsed" desc="Generated Code"> 
private void initComponents() { 

    jComboBox1 = new javax.swing.JComboBox(); 

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); 

    jComboBox1.setEditable(true); 

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); 
    getContentPane().setLayout(layout); 
    layout.setHorizontalGroup(
     layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
     .addGroup(layout.createSequentialGroup() 
      .addGap(87, 87, 87) 
      .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 215, javax.swing.GroupLayout.PREFERRED_SIZE) 
      .addContainerGap(98, Short.MAX_VALUE)) 
    ); 
    layout.setVerticalGroup(
     layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
     .addGroup(layout.createSequentialGroup() 
      .addGap(108, 108, 108) 
      .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) 
      .addContainerGap(172, Short.MAX_VALUE)) 
    ); 

    pack(); 
}// </editor-fold> 

/** 
* @param args the command line arguments 
*/ 
public static void main(String args[]) { 
    /* Set the Nimbus look and feel */ 
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> 
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. 
    * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
    */ 
    try { 
     for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { 
      if ("Nimbus".equals(info.getName())) { 
       javax.swing.UIManager.setLookAndFeel(info.getClassName()); 
       break; 
      } 
     } 
    } catch (ClassNotFoundException ex) { 
     java.util.logging.Logger.getLogger(test2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } catch (InstantiationException ex) { 
     java.util.logging.Logger.getLogger(test2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } catch (IllegalAccessException ex) { 
     java.util.logging.Logger.getLogger(test2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } catch (javax.swing.UnsupportedLookAndFeelException ex) { 
     java.util.logging.Logger.getLogger(test2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } 
    //</editor-fold> 

    /* Create and display the form */ 
    java.awt.EventQueue.invokeLater(new Runnable() { 
     public void run() { 
      new test2().setVisible(true); 
     } 
    }); 
} 
// Variables declaration - do not modify 
private javax.swing.JComboBox jComboBox1; 
// End of variables declaration 
}