Alwyn Mathew
Alwyn Mathew

Reputation: 300

List objects in a combobox in java

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

Answers (1)

Paul Samsotha
Paul Samsotha

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:

Upvotes: 1

Related Questions