0

我想要的是一个可编辑的 jcombobox。当用户输入它时,它应该搜索数据库并在数据库中显示以用户输入的文本开头的名称。例如。: 如果用户输入 'a' 。然后 jcombobox 应该显示数据库中以 'a' 开头的所有名称。

如果数据库包含名称 aaron,aidan,kim 。当用户键入“a”时,组合框应建议名称 aaron 和 aidan

    /*
     * 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: Attempt to mutate in notification

4

1 回答 1

0

自动建议类型可编辑 Jcombo 框 - 根据您键入的内容显示来自数据库的建议。

 /*
 * 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
}
于 2013-06-01T18:31:18.830 回答