Text Field With Autosuggest

荒凉一梦 提交于 2019-12-13 04:55:29

问题


What i want is an editable jcombobox. As the user types into it, it should search the database and display the names in the database that starts with the text that was typed in by the user. eg. : If the user types in 'a' . Then jcombobox should display all the names in the database that starts with 'a' .

If database contains the names aaron,aidan,kim . When user types 'a' then the combobox should suggest names aaron and 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                   


}

When i run this , Only the first name in the database that begins with the letter typed in is shown by jcombobox. An error follows errorjava.lang.IllegalStateException: Attempt to mutate in notification


回答1:


Auto Suggest Type Editable Jcombo Box - Displays Suggestions From Database Based On What You Type.

 /*
 * 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
}


来源:https://stackoverflow.com/questions/16801951/text-field-with-autosuggest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!