Im using a JComboBox
to search a query from a sql database. Here is my code.
private void srKeyTyped(java.awt.event.KeyEvent evt){
sr.remove
Use an ActionListener
instead of the looking for the key press. When a combobox's selection is edited it will fire an ActionEvent
when the editing is done.
When you get this part working, you should move this logic off to another thread and populate the combobox's items when it returns. Otherwise your UI will hang while the SQL query occurs.
The reasons for your problems are the following:
sch
is always empty is because you are calling sr.removeAllItems();
before you call String sch = ((JTextField)sr.getEditor().getEditorComponent()).getText();
. This means that the contents of the JComboBox
is cleared (along with the selection) before you get what is selected.
Solution: Call sr.removeAllItems();
AFTER you have got the selected item.
The combo box becomes empty because you call sr.setSelectedItem(null);
at the end after you have repopulated it.
Solution: If you want the entered text then sr.getEditor().setItem(scr);
Only and idea but try to enclose the contents of the method in an if statement
and check if the Enter key
is pressed. That way the method contents will only execute after the desired string is input and not EVERY time a key is pressed.
Got the solution. This code works fine.
private void srKeyTyped(java.awt.event.KeyEvent evt){
String sch = ((JTextField)sr.getEditor().getEditorComponent()).getText();
String schh = "SELECT * FROM tbl WHERE name LIKE '" + sch + "%';";
search = conn.getQuery(schh);
sr.removeAllItems();
try {
while (search.next()) {
String item = search.getString("name");
sr.addItem(item);
}
} catch (SQLException ex) {
Logger.getLogger(dataprocess.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(sch);
sr.setSelectedItem(null);
sr.setPopupVisible(true);
((JTextField)sr.getEditor().getEditorComponent()).setText(sch);
}
Thanks to Skepi,Kleopatra, Guillaume Polet