2015-02-07 35 views
0

我想放入一個jcombobox,名字和使用id來鏈接選項選擇和名稱。 我得到了數據庫的數據,但我不知道添加項目的方式。如何將一個索引放入java的jcombobox中?

我嘗試寫一個項目,有兩個參數,但在組合框中出現的類名,而不是價值:

這是我的代碼

rs = (ResultSet) stmt.executeQuery(); 

    while (rs.next()) { 

     cbHabitaciones.addItem(new Item(rs.getInt("id"), rs.getString("tipo") +" - " +rs.getString("precio"))); 
      } 
+0

顯示「Item」類。 – alterfox 2015-02-07 14:40:31

回答

0
你將

最簡單的方法覆蓋toString()該類的方法,您正在將這些實例放入JCombo的模型中。這樣你就可以得到每個物品的「好名字」。
當然,該課程應包含每個項目所需的所有內容,例如ID和名稱。在選擇更改時,您可以使用所選項目的ID。
如果您不能覆蓋'toString()',或者想要從演示文稿對象中分離出您已有的對象(例如,如果它們是DTO),請僅使用您需要的內容創建自己的類。

public class User { 
    private int id; 
    private String name; 

    public User(int id, String name) { 
     this.id = id; 
     this.name = name; 
    } 

    public int getId() { 
     return this.id; 
    } 

    public String getName() { 
     return this.name; 
    } 

    public String toString() { 
     return this.getName(); 
    } 
} 
+0

它不起作用。我複製我的代碼在問題 – sdelcueto 2015-02-07 14:38:42

+0

當我做出這個JOptionPane.showMessageDialog(null,cbHabitaciones.getSelectedIndex());,只出現數組indent,而不是我的數據庫ID:S – sdelcueto 2015-02-07 14:40:35

+0

嗯,這就是你問 - 'getSelectedIndex() '。使用'getSelectedItem()'來代替,轉換爲你的類,然後得到id。 – alterfox 2015-02-07 14:41:57

相關問題