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;
}
如何使這項工作?
謝謝