views:

25

answers:

1

Hi Everyone,

I'm trying to populate my jComboBox with the following items:

public class DropDownItem {

private String text;
private int id;

public void setText(String text) {
    this.text = text;
}

public void setId(int id) {
    this.id = id;
}

public String toString() {
    return text;
}

public int getId() {
    return id;
}


public boolean equals(Object i) {
    System.out.println("i is: " + i);

    if(i instanceof Integer) {
        if((Integer)i == (Integer)id) {
        System.out.println("It's me!");
        return true;
        }
        else {
            System.out.println("I was asked if I was " + (Integer)i + " but I'm " + id + " as I'm " + text);
            return super.equals(i);
        }
    }
    else return super.equals(i);
}

}

However I'm having trouble using jComboBox's setSelectedItem. I pass setSelectItem an int, and as you can see from above, I've tried to make sure that it gets selected when it's the correct one. The problem I'm having, is that only the currently selected item is checked, which to me is very strange. I verified that by added the print statement, which only gets printed out once..

Any ideas?

Thanks

+1  A: 

Your implementation of the equals() method is wrong. The Object will never be an Integer, it will always be a DropDownItem. I would guess equality would be checked by comparing the "id" of the current Object with the "id" of the Object passed to the equals() method.

Edit: If you add a new item to the model and want to select it your code should be something like:

DropDownItem item = new DropDownItem();
item.setId(1);
item.setText("one");
comboBox.addItem( item );
comboBox.setSelectedItem( item );

Edit2: the equals method will look something like:

DropDownItem item = (DropDownItem)i;

return getId() == item.getId();

Now when you get the integer value from the database you can just do:

DropDownItem item = new DropDownItem();
item.setId(???);
comboBox.setSelectedItem( item );

Even though you didn't specify the description, the item will be selected because the equals method only cares about the id.

camickr
But the thing is, is that I'm passing setSelectedItem an integer (read from a database). And also, the object is an Integer once, as my print statement is executed.
jtnire
Maybe the object from the database is an Integer, but the Objects in the combo box model are "DropDownItem". So an Integer can never be equal to a DropDownItem. See "edit" from above for sample code.
camickr
Hmm ok then, so how would I go about selected the item based on just the integer from the database?
jtnire
I explained that in my first reply. You need to implement the equals method properly to return true when the "id" values are the same. Then when you get an integer from the database you can create a new DropDownItem and just set the ID value and then use the setSelectedItem with that Object.
camickr