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
 
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.
 
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,969
Messages
2,570,161
Members
46,705
Latest member
Stefkari24

Latest Threads

Top