title: Autosuggestion combobox with retrieve the values from mysql database
body: <p>Am using the following java program for Autosuggestion combobox with retrieve the values from mysql database.the Auto Suggestion working properly.If i type 'A' in the combobox means the list will show the all names starting with 'A'.i add the label in that form.If i select the one name in combo box means the corresponding Id will display in the Label. My problem is i have the four names with starting 'A' in my Sql database table,if I select that 'A' starting name that will show correct Id.but I clear the combobox text column and type 'B' means it show the all name starting with 'B' but it I click the "B" started name it can't display the correct ID,It display the ID for 'A' starting name.because I get the Id using getSelectedIndex().how to get the correct ID for all names in auto suggest combobox?</p>
  
  <pre><code>package combo;
  import java.sql.*;
  import java.awt.*;
  import java.awt.event.*;
  import java.util.*;
  import javax.swing.*;
  
  
  public class comboauto extends javax.swing.JFrame {
           Vector  v=new Vector();
           Vector v1=new Vector();
           Statement TmpSqlStmnt;
           ResultSet TmpSqlRs;
           Connection con;
           int CateId;
           JTextField Txt01;
  
      public comboauto() {
          initComponents();
      }
     public void AutoSuggest() {
                 Txt01=(JTextField)Cbx01.getEditor().getEditorComponent();
                 Txt01.addKeyListener(new KeyAdapter() {
                  public void keyTyped(KeyEvent e)
                  {
                   EventQueue.invokeLater(new Runnable()
                   {
                     public void run() {
                     String text =Txt01.getText().toUpperCase();
                     if(text.length()==0)
                               {
                                  Cbx01.hidePopup();
                                  setModel(new DefaultComboBoxModel(v1), "");
                               }
                               else{
                                  DefaultComboBoxModel m = getSuggestedModel(v1, text);
                                 if(m.getSize()==0 ) {
                                 Cbx01.hidePopup();
                                   }
                                  else{
                                            setModel(m, text);
                                           Cbx01.showPopup();
                                       }
                                   }
                               }
                            });
  
                      }
                  public void keyPressed(KeyEvent e)
                   {
                      String text = Txt01.getText();
                      int code = e.getKeyCode();
                      if(code==KeyEvent.VK_ENTER) {
                      if(!v1.contains(text)) {
                      v1.addElement(text);
                     // setModel(getSuggestedModel(v1, text), text);
              }
                      hide_flag = true;
          }else if(code==KeyEvent.VK_ESCAPE) {
           hide_flag = true;
          }else if(code==KeyEvent.VK_RIGHT) {
              for(int i=0;i&lt;v1.size();i++) {
                  String str = (String) v1.elementAt(i);
                  if(str.startsWith(text))
                  {
         //            Cbx01.setSelectedIndex(-1);
                     Txt01.setText(str);
                     return;
                  }
              }
          }
              }
        });
  
  
        try{
          Class.forName("com.mysql.jdbc.Driver");
          con =DriverManager.getConnection("jdbc:mysql://localhost:3306/project","root","root");
          TmpSqlStmnt=con.createStatement();
          TmpSqlRs=TmpSqlStmnt.executeQuery ("SELECT CateId,CateName FROM Cust_Masterrecord ORDER BY CateName");
          System.out.println("DB Connected");
          Cbx01.removeAllItems();
          TmpSqlRs.first();
             if (Cbx01.getItemCount() == 0)
             {
  
                 //Cbx01.addItem("");
               do
                {
                 // String s= TmpSqlRs.getString("CateName");
                  Cbx01.addItem(TmpSqlRs.getString("CateName"));
                  CateId=TmpSqlRs.getInt("CateId");
                  v.add(CateId);
                  // s.valueOf(CateId);
                  // System.out.println(s.valueOf(CateId));
                  // System.out.println(CateId);
                  // for(int i=0;i&lt;CateName.length;i++){
                  v1.addElement(TmpSqlRs.getString("CateName"));
                   //}
                    Cbx01.addItemListener(new ItemListener() {
                    public void itemStateChanged(ItemEvent e) {
                                       if (e.getStateChange() == ItemEvent.SELECTED) {
  
                                           //Cbx01.getItemCount();
                                           //System.out.println(Cbx01.getItemCount());
                                           //Cbx01.getSelectedItem();
                                           //System.out.println(Cbx01.getSelectedItem());
  
                                           Cbx01.getSelectedIndex();
                                          //System.out.println( Cbx01.getSelectedIndex());
                                          Lbl01.setText(v.get( Cbx01.getSelectedIndex()).toString());
                                        //System.out.println(v.get( Cbx01.getSelectedIndex()).toString());
                                      }
                                  }
                              });
  
         }while(TmpSqlRs.next());
       }else{Cbx01.addItem("Records Not Available");}
     }catch(Exception e){
      System.out.println(e);
    }
  
  
      }
  
  private boolean hide_flag = false;
         private void setModel(DefaultComboBoxModel mdl, String str) {
          Cbx01.setModel(mdl);
          //Cbx01.setSelectedIndex(-1);
          Txt01.setText(str);
      }
  private static DefaultComboBoxModel getSuggestedModel(java.util.List&lt;String&gt; list, String text) {
          DefaultComboBoxModel m = new DefaultComboBoxModel();
          for(String s: list) {
              if(s.startsWith(text)) m.addElement(s);
          }
          return m;
      }
  
  
  
  
      @SuppressWarnings("unchecked")
      // &lt;editor-fold defaultstate="collapsed" desc="Generated Code"&gt;                          
      private void initComponents() {
  
          Cbx01 = new javax.swing.JComboBox();
          Lbl01 = new javax.swing.JLabel();
  
          setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
  
          Cbx01.setEditable(true);
          Cbx01.addPopupMenuListener(new javax.swing.event.PopupMenuListener() {
              public void popupMenuCanceled(javax.swing.event.PopupMenuEvent evt) {
              }
              public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {
                  Cbx01PopupMenuWillBecomeInvisible(evt);
              }
              public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {
                  Cbx01PopupMenuWillBecomeVisible(evt);
              }
          });
          Cbx01.addComponentListener(new java.awt.event.ComponentAdapter() {
              public void componentMoved(java.awt.event.ComponentEvent evt) {
                  Cbx01ComponentMoved(evt);
              }
          });
          Cbx01.addItemListener(new java.awt.event.ItemListener() {
              public void itemStateChanged(java.awt.event.ItemEvent evt) {
                  Cbx01ItemStateChanged(evt);
              }
          });
  
          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(49, 49, 49)
                  .addComponent(Cbx01, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                  .addGap(45, 45, 45)
                  .addComponent(Lbl01, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE)
                  .addContainerGap(103, Short.MAX_VALUE))
          );
          layout.setVerticalGroup(
              layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addGroup(layout.createSequentialGroup()
                  .addGap(110, 110, 110)
                  .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                      .addComponent(Cbx01, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                      .addComponent(Lbl01, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                  .addContainerGap(170, Short.MAX_VALUE))
          );
  
          pack();
      }// &lt;/editor-fold&gt;                        
  
      private void Cbx01ItemStateChanged(java.awt.event.ItemEvent evt) {                                       
  //Lbl01.setText(v.get( Cbx01.getSelectedIndex()).toString());        // TODO add your handling code here:
      }                                      
  
      private void Cbx01ComponentMoved(java.awt.event.ComponentEvent evt) {                                     
  //Lbl01.setText(v.get( Cbx01.getSelectedIndex()).toString());        // TODO add your handling code here:
      }                                    
  
      private void Cbx01PopupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {                                                 
      //   Lbl01.setText(v.get( Cbx01.getSelectedIndex()).toString()); // TODO add your handling code here:
      }                                                
  
      private void Cbx01PopupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {                                                   
        // Lbl01.setText(v.get( Cbx01.getSelectedIndex()).toString()); // TODO add your handling code here:
      }                                                  
  
      /**
      * @param args the command line arguments
      */
      public static void main(String args[]) {
          java.awt.EventQueue.invokeLater(new Runnable() {
              public void run() {
                 comboauto Tmpobj1= new comboauto();
                 Tmpobj1.AutoSuggest();
                 Tmpobj1.setVisible(true);
  
              }
          });
      }
  
      // Variables declaration - do not modify                     
      private javax.swing.JComboBox Cbx01;
      private javax.swing.JLabel Lbl01;
      // End of variables declaration                   
  
  }
  </code></pre>