Reputation: 300
I have a Combobox and i want to fill it with object.
I have tried but i couldn't make it.
Swing java program:
String query="select ProductId,Productname from maintable";
PreparedStatement pstmt = null;
pstmt = con.prepareStatement(query);
ResultSet res=pstmt.executeQuery();
while(res.next())
{
String productName = res.getString(1);
String productId = res.getString(2);
comboitem comboval = new comboitem(productId, productName);
combo.addElement(comboval); // ERROR
}
Class comboitem is the class with which Object is created.
public class comboitem
{
private String productId;
private String productName;
public comboitem (String productId, String productName)
{
this.productId = productId;
this.productName = productName;
}
public String getProductId() {
return productId;
}
public String getProductName() {
return productName;
}
@Override
public String toString() {
return productName;
}
}
I'm using CComboBox here. Can I list objects in CComboBox?
Upvotes: 1
Views: 1761
Reputation: 209004
You tagged Java, so I'm going to assume you mean JComboBox
and not C++ CComboBox
. That being said, the only error I can see arising from that one method call, again assuming combo
is a JComboBox
is that JComboBox
has no addElement
method. You probably mean to be using a DefaultComboBoxModel
which does have an addElement
method. So you should do something like
MutableComboBoxModel<comboitem> model = new DefaultComboBoxModel<comboitem>();
while(res.next())
{
String productName = res.getString(1);
String productId = res.getString(2);
comboitem comboval = new comboitem(productId, productName);
model.addElement(comboval); // ERROR
}
combo.setModel(model);
Asides:
Follow Java naming convention. Class names begin with capital letters and should use CamelCasing.
Seem to me either you have two accounts - which is completely unacceptable, or you and your classmate are working on the same thing. Either way, they answer given by @HovercraftFullOfEels was more than suitable. If you didn't understand, you should ask more question. Or you could simple go to the tutorial, and see How to use Combo Boxes
Upvotes: 1