JTable单元中的即时搜索/自动完成

时间:2015-01-11 14:18:43

标签: java swing autocomplete jcombobox

我正在尝试在具有即时搜索功能的JTable单元格中使用搜索,以便在单元格中输入的字符串返回下方下拉列表中的匹配选项,用户可以从中选择一个值。

我在单元格中使用了可编辑的JCombobox但没有获得所需的结果。我必须单击单元格以显示选项,这也显示所有值。

如果有人知道如何做到这一点,我会感激任何帮助或指导。

public class AutocompleteInternal extends javax.swing.JInternalFrame {
public static JComboBox combo = new JComboBox();

LoginConnection login = new LoginConnection();
/**
 * Creates new form AutocompleteInternal
 */
public AutocompleteInternal() {
    initComponents();
    combo.setEditable(true);
  combo.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {
      @Override
        public void keyReleased(KeyEvent event) {
            System.out.println("hello"+event.getKeyChar());
            System.out.println("hello"+event.getKeyCode());
            String comboName = combo.getEditor().getItem().toString();
            if(event.getKeyCode()>=65 && event.getKeyCode()<=90 || event.getKeyCode()>=95 && event.getKeyCode()<=105 || event.getKeyCode()==8){
             combo.setModel(fatchData(comboName));
              if(combo.getItemCount()>0)
              {

                  combo.showPopup();
                  if(event.getKeyCode()!=8)
                   {
                       ((JTextComponent)combo.getEditor().getEditorComponent()).select(comboName.length(), combo.getEditor().getItem().toString().length());
                       combo.requestFocusInWindow();

                   }
                else{
                      combo.requestFocusInWindow();
                     combo.getEditor().setItem(comboName);

                   }
              }
             else
                {
                    combo.requestFocusInWindow();
                    combo.addItem(comboName);

                }

            }  
        }
  });
}

public DefaultComboBoxModel fatchData(String ComboName)
{
  DefaultComboBoxModel modulo = new DefaultComboBoxModel();
  try
 {
  System.out.println("hello");
  ResultSet rs=null;
  Connection con=null;
 con=LoginConnection.getConnection();
 if(con!=null)
 {
  System.out.println("select name from product where name Like '%"+ComboName+"'");
 //String sql ="select code,name from product where id < 100"; 

      //Object obj = combo.getEditor().getItem().toString();  
     // System.err.println("objectName"+obj);
  PreparedStatement pst= con.prepareStatement("select name from product where  name Like '"+ComboName+"%'",ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
     System.out.println("hello");
  rs = pst.executeQuery();

  while(rs.next()){String pName= rs.getString("name");

     modulo.addElement(pName);

 }
 }
 else
 {
     System.out.println("con not found");
 }
 }

 catch(SQLException e)
 {
     System.err.println("Exception "+e);         
 }
  catch(Exception ee)
 {
     System.err.println("Exception:: "+ee);         
 }


return modulo;

}

当输入的字符串与数据库表中的可用选项不匹配时,celleditor(JcomboBox)失去焦点并且不执行任何操作,即它变得无用。

0 个答案:

没有答案