问题
I want to get name and id from database and add it to JCombobox
. For this i used
public void add_Category(JComboBox cmb) {
try {
String query = "SELECT * FROM categories";
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String Txtcmb = rs.getString(2).trim();
int idCmb = rs.getInt("id");
Item comboItem = new Item(idCmb, Txtcmb);
cmb.addItem(comboitem); //This line add only 1 object in combocox but i have 5 in my database
}
} catch(Exception e) {
}
}
Item.java
public class Item {
private int id;
private String description;
public Item(int id, String description) {
this.id = id;
this.description = description;
}
public int getId() {
return id;
}
public String toString() {
return description;
}
}
Now the problem is when I add object into combobox it add only one object while I have 5 object into my database.
It display me only one item in combobox instead of 5. One more thing i want to clear if I add only string into database like comboItem.addItem(Txtcmb);
then it works fine
Any idea will be appreciated. Thanks in advance.
回答1:
Thanks to all. Actually i was using Item comboItem[]; before while and and Item comboItem = new Item(idCmb, Txtcmb); inside while. When i remove Item comboItem[]; line and clean and buid my project again then it start working. Again thanks for your concern.
来源:https://stackoverflow.com/questions/25738472/get-id-and-data-from-database-and-add-to-jcombobox