Objects in a JComboBox


I

Ike

I want to populate a JComboBox with Objects like the following:

class MyThings{
public int myint;
public String mystring;
}

Suppose I have an ArrayList of these things. I put the mystring Strings into
the JComboBox, which then gets sorted. However, when a selection is made in
the JCombobox, I want to retrieve the myint values (note - the myint values
are unique to each element, the mystring values may not be, i.e. it is much
like a relational database record).

Any idea how best to accomplish this? Thanks Ike
 
Ad

Advertisements

I

Ike

make an arraylist of MyThings.....
then, Collections.sort() on the arraylist, based on comparing mystring...
iterate through the now sorted ArrayList, jComboBox.additem(...mystring);
When an element is selected in the JComboBox, get the
JComboBox.getSelectedIndex()...this is the index into the sorted ArrayList
where the myint corresponding the the selected mystring can be found......
 
J

Jeff

Objects can be placed in a JComboBox. Just make sure your object
implements the toString() method appropriately for display in the list.
Then JComboBox.getSelectedItem() will return the selected MyThing.
There's really nothing to it.
 
Ad

Advertisements

I

Ike

Ah, right...thats the better way. Thamnks, Ike

Jeff said:
Objects can be placed in a JComboBox. Just make sure your object
implements the toString() method appropriately for display in the list.
Then JComboBox.getSelectedItem() will return the selected MyThing.
There's really nothing to it.
 

Top