Question

I am populating a combobox using a DefaultComboBoxModel and a custom Item. Each item contains an id and a name. I am iterating through a table, and based on a selection, I would like to remove selected elements from the combobox. For the items I want to remove, I have the ID and Name from the table I am iterating through. I have tried using removeItem which takes in an object. I pass the ID and Name into my custom Item constructor, but that does not seem to work. Can anyone tell me what I am missing here?

Code for populating combobox:

Vector<Object> companyList = new Vector<Object>();
        while(rs.next()){
            companyList.addElement(new Item(rs.getInt(1),rs.getString(2)));
        }
DefaultComboBoxModel cmod = new DefaultComboBoxModel(companyList);
        companyName.setModel(cmod);

Code for custom Item:

class Item
{
    private int id;
    private String name;

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

    public int getId()
    {
        return id;
    }

    public String getName()
    {
        return name;
    }

    public String toString()
    {
        return name;
    }
}

Code for removing Item (hard-coded for this example):

 companyName.removeItem(new Item(50002,"ALLIED WASTE SYSTEMS"));

removeItem says it takes in an Object so I am not sure why this won't work. Any help would be appreciated!

Was it helpful?

Solution

Your class Item does not override equals() and hashCode() so that "equal" items compare as equal. You need to implement these two methods to satisfy the contract required by collection classes.

OTHER TIPS

you can use a temporary list, which won't contain that element you want to remove...

then change your combobox model with that temporary list...

DefaultComboBoxModel cmod = new DefaultComboBoxModel(tempCompanyList);
    companyName.setModel(cmod);

you can use the removeElementAt method, as they already mentioned it...:D

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top