0

The problem is that when I enter some character in JComboBox then it just autoselected, again I enter other text then it replace the first character, so I am not able to type multiple character in JComboBox(my JComboBox is editable)...

pleasw help.

private void combo1KeyReleased(java.awt.event.KeyEvent evt) 
    {
        if((evt.getKeyChar() >= '0' && evt.getKeyChar() <= '9')||(evt.getKeyChar() >= 'a' && evt.getKeyChar() <= 'z')||(evt.getKeyChar() >= 'A' && evt.getKeyChar() <= 'Z')||evt.getKeyCode() == KeyEvent.VK_BACK_SPACE)
        {
          try
          {
      Connection con=null;
      ResultSet rs;
      con=LoginConnection.getConnection();
          String srch=""; 
          if(con!=null)
           {
              srch=(String)combo1.getEditor().getItem();
              System.out.println("value to search:"+srch);
              String s="select name from supplier where name like '%"+srch+"%' order by name";
              PreparedStatement pst=con.prepareStatement(s,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
              rs=pst.executeQuery();

              int itemCount = combo1.getItemCount();
                   System.out.println("no of value="+itemCount);
                   for(int i=0;i<itemCount;i++){  //removing items
                         combo1.removeItemAt(0);
                   }  
              if(!rs.next())
                {  
                  System.out.println("----------------------No Data Found");  
                }
                else
                {

                   rs.beforeFirst();
                   while(rs.next())
                   {  
                     combo1.addItem(rs.getString(1));  // addind item
                     System.out.println("while value is:"+rs.getString(1));
                   }

                 }
              combo1.getEditor().setItem(srch);// adding item in field which i have fetched using getItem method 
                   combo1.showPopup();
           } 
          }
          catch(Exception e)
          {
               System.out.println("ex:"+e); 
          } 
         }
}     
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • First problem - don't use key listeners with text components, this is not the way this works. Instead, consider using a `DocumentFilter` or a `DocumentListener`. Personally, a `JComboBox` is a really poor choice for this, as it will constantly try and replace the text in the editor field with what it thinks was last selected (or nothing if nothing was selected) – MadProgrammer Aug 19 '14 at 05:30
  • [this](http://www.orbital-computer.de/JComboBox/) might be a better choice – MadProgrammer Aug 19 '14 at 05:32
  • The question should be "How to implement an autocomplete widget with Swing?". I'd say this is a dupblicate of http://stackoverflow.com/questions/485530/how-could-i-implement-autocompletion-using-swing. – BetaRide Aug 19 '14 at 05:37

0 Answers0