The moose likes Swing / AWT / SWT and the fly likes Same value in JComboBox Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Same value in JComboBox" Watch "Same value in JComboBox" New topic
Author

Same value in JComboBox

Jennifer Sohl
Ranch Hand

Joined: Feb 28, 2001
Posts: 455
I have a JComboBox with names of vendors in it. There happens to be a couple of cases where the vendor names are the same, but have different ID numbers:

Store Kraft Mfg
Store Kraft Mfg

When I try to pick on the second one, it always kicks me back up to the first one listed. What can I do to change this behavior?

Thanks!
Michael Dunn
Ranch Hand

Joined: Jun 09, 2003
Posts: 4632
it sounds like you are adding the items e.g "Store Kraft Mfg" as a String,
then using getSelectedIndex() for the index of a data structure.

This will always return the first occurence of "Store Kraft Mfg".

you need to add the object to the combobox, and use getSelectedItem().
Add a toString() method to the object. toString() will return eg "Store Kraft Mfg"
which is what appears in the comboBox.

here's a simple example, click on the 2nd of the "Store Kraft Mfg" in both
comboBoxes to display the ID.
The one on the left will be wrong, the one on the right will be correct.

Jennifer Sohl
Ranch Hand

Joined: Feb 28, 2001
Posts: 455
Okay, I've got the values in my JComboBox working correctly now, so if they're the same value, it doesn't always choose the first one. Now, I'm trying to figure out, if I pull a vendor name from a database as a String value and want to use that to set the selected item in the combo box, what is the best way to do that? Right now my JComboBox has a bunch of Vendor objects sitting in it and I'm not quite sure how to go about setting the selected item.
Thanks!
[ April 21, 2006: Message edited by: Jennifer Sohl ]
Hari Surendran
Greenhorn

Joined: Feb 09, 2003
Posts: 3
Since you need to have the same display values for two different drop down items, you need to use the objects instead of strings. To set a particular item on the dropdown using the data read from database, you can use the setselctedItem(Object obj) method. Just construct an object using the value read from database and call the setselctedItem(Object obj) method.

Since this newly constucted object is a different object(instance) from what is sitting inside your Jcombobox, you will have to implement an equals() method in the Vendor class in addition to the toString() method. This equals method will check whether the vendor IDs are equal.

Hope this will help.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Same value in JComboBox