使用JComboBox
來搜索來自sql數據庫的查詢。這是我的代碼。將JComboBox用作搜索框
private void srKeyTyped(java.awt.event.KeyEvent evt){
sr.removeAllItems();
String sch = ((JTextField)sr.getEditor().getEditorComponent()).getText();
String schh = "SELECT * FROM tbl WHERE name LIKE '" + sch + "%';";
search = conn.getQuery(schh);
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);
}
sr.setSelectedItem(null);
sr.setPopupVisible(true);
System.out.println(sch);
}
sr
= JComboBox中
但是當我在組合框中鍵入一個字母,它增加了在數據庫中的所有項目。我開始知道System.out.println(sch);
總是給出一個空字符串。只要我鍵入一個字母,組合框的文本字段變空(我不能用兩個字母輸入一個單詞)。如何解決這個問題?謝謝。
removeAllItems可能清除編輯器(沒掏,雖然) – kleopatra
也許只是一味的文本設置重新編輯,將所有物品和展示後彈出窗口? 'removeAllItems()'確實會清除文本 –
在事件派發線程上執行數據庫查詢並不是一個好主意,當然不是每次擊鍵都會執行。此外,你爲什麼有權訪問'KeyEvent'。 「JComboBox」的編輯器支持「DocumentListener」,它幾乎總是更好的選擇 – Robin