[英]How to populate data in a JComboBox?
我已經創建了一個GUI,並在外部有一個數據庫,可以從中獲取數據。 我正在NetBeans中使用GUI構建器來執行此操作。 有誰知道用來自數據庫的值填充jComboBox的簡單方法嗎? 當我運行項目時,沒有錯誤,但組合框保持為空。
這是使用折扣名稱設置組合框的代碼:
public void setDiscountNames(String type, JComboBox cbox) {
cbox.removeAllItems();
ArrayList<Discount> names = new ArrayList<Discount>();
try {
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/abpp034?user=abpp034&password=120001772");
stmt = con.prepareStatement("SELECT Name FROM Discount WHERE Type = \"" + type + "\"");
rs = stmt.executeQuery();
while(rs.next()){
cbox.addItem(rs.getString("Name"));
}
} catch (SQLException ex) {
Logger.getLogger(Model.class.getName()).log(Level.SEVERE, null, ex);
}
}
它位於與jComboBox對象不同的類中。 此類稱為模型。
這是我以稱為DiscountGUIView的形式調用setDiscountNames方法的地方:
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt){
model.setDiscountNames("Fixed", jComboBox1);
}
好的(更新)查詢確實會打印結果:
run:
旅行標准固定標准建造成功(總時間:1秒)
您的SELECT
查詢可能未返回任何結果。 為了驗證這一點,您可以在while (rs.next())
循環內添加日志記錄語句。 我的SQL知識有點生銹,但是我記得對字符串文字使用'
(單引號),而在語句中使用了"
(雙引號)。
除此之外,我還看到了可能導致問題的幾件事:
PreparedStatement
的SQL代碼不應通過字符串串聯創建。 而是使用?
用於將被替換為語句的參數值,例如
stmt = con.prepareStatement("SELECT Name FROM Discount WHERE Type = ?"); stmt.setString(1, type); // first (and only) parameter rs = stmt.executeQuery();
強烈建議您在使用完JDBC資源后,明確關閉它們。 為此,您需要在catch (SQLException ...)
之后添加一個finally
塊,例如
} finally { try { if (rs != null) rs.close(); } catch (SQLException ignore) {} try { if (stmt != null) stmt.close(); } catch (SQLException ignore) {} try { if (conn != null) conn.close(); } catch (SQLException ignore) {} }
或者,最好使用try-with-resources
語句(如果使用的是Java 7和更高版本):
try (Connection con = DriverManager.getConnection(...)) { // ... try (PreparedStatement stmt = con.prepareStatement("SELECT Name FROM Discount WHERE Type = ?")) { // ... try (ResultSet rs = stmt.executeQuery()) { while (rs.next()) { // processing } } } } catch (SQLException) { Logger....; } // notice no finally block; resources are closed automatically
嘗試將元素動態添加到組合框時,請使用MutableComboBoxModel.addElement
JComboBox box = new JComboBox(new DefaultComboBoxModel());
....
MutableComboBoxModel model = (DefaultComboBoxModel)box.getModel();
while (rs.next()) {
model.addElement(rs.getString("Name"));
}
要刪除所有元素,您也可以這樣做
((DefaultComboBoxModel)box.getModel).removeAllElements();
使用模型方法將觸發必要的更改以更新用戶界面
編輯:這是您的基本錯誤..您正在ActionPerformed中調用該方法!
classConstructor(){
setDiscountNames("Fixed", jComboBox1); // call this method here.. This will work.
}
如果值打印正確,請嘗試此操作。
List<String> strings = new ArrayList<String>();
while(rs.next()){
strings.add(rs.getString("Name")); // Confirm if "Name" is valid
}
cbox.addItem(strings);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.