2011-12-20 59 views
1

我正在为我的问题寻找解决方案。我使用NetBeans7,我尝试使用带有setEditable(true)的JComboBox。我需要该用户在JcomboBox上一次输入一个单词,并执行SELECT LIKE并返回一个包含JCombo所有结果的List。JComboBox做出选择?

我没有看到这一点:Set Size of JComboBox PopupMenu

但我无法实现。

这里如何我试图。

//the model 
public class JComboModelFuncoes extends AbstractListModel implements ComboBoxModel{ 
    private Object selectedItem; 
    private List<Funcoes> listaFuncoes = null; 

    public JComboModelFuncoes(List<Funcoes> lista){ 
     listaFuncoes = new ArrayList<Funcoes>(); 
     listaFuncoes.addAll(lista); 
    } 

    @Override 
    public int getSize() {   
     return listaFuncoes.size(); 
    } 

    @Override 
    public Object getElementAt(int index) { 
     return listaFuncoes.get(index); 
    } 

    @Override 
    public void setSelectedItem(Object anItem) { 
     selectedItem = anItem; 
    } 

    @Override 
    public Object getSelectedItem() { 
     return selectedItem; 
    } 

} 


//here JComboBox 
comboPesquisa.setMaximumRowCount(10); 
    final JTextField tf;  
    tf = (JTextField)comboPesquisa.getEditor().getEditorComponent(); 
    tf.setDocument(new LimitaNroCaracteres(50)); 
    tf.addKeyListener(new KeyAdapter() { 
     public void keyReleased(KeyEvent e){ 
      comboPesquisa.removeAllItems(); 
      List<Funcoes> lista = new FuncoesDAO().retornaFuncao(tf.getText());  
      for(Funcoes f : lista){ 
       comboPesquisa.addItem(f.getFuncao()); 
      } 
      comboPesquisa.setPopupVisible(true); 
     }  
    }); 

//here my DAO that return all results 
public List<Funcoes> retornaFuncao(String funcao){ 
     List<Funcoes> lista = new ArrayList<Funcoes>(); 
     PreparedStatement stm = null; 
     ResultSet rs = null; 
     try{ 
      stm = this.con.prepareStatement("SELECT * FROM funcoes WHERE funcao LIKE ?"); 
      stm.setString(1, "%" + funcao + "%"); 
      rs = stm.executeQuery(); 
      while(rs.next()){ 
       Funcoes f = new Funcoes(); 
       f.setIdFuncao(rs.getLong("id_funcao")); 
       f.setFuncao(rs.getString("funcao")); 
       lista.add(f); 
      }    
     }catch (SQLException e){ 
      JOptionPane.showMessageDialog(null, "Erro tentando consultar função", "Erro", JOptionPane.ERROR_MESSAGE); 
     }finally{ 
      try { 
       rs.close(); 
       stm.close(); 
      } catch (SQLException ex) { 
       Logger.getLogger(FuncoesDAO.class.getName()).log(Level.SEVERE, null, ex); 
      } 

     } 
     return lista; 
    } 

如何使这项工作?

谢谢

回答