Forums Register Login

Same value in JComboBox

+Pie Number of slices to send: Send
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!
+Pie Number of slices to send: Send
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.

+Pie Number of slices to send: Send
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 ]
+Pie Number of slices to send: Send
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.
There's a way to do it better - find it. -Edison. A better tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 4026 times.
Similar Threads
how to store datecombobox in an arraylist of type combobox
I can't load a file with getResource
jdk on linux 8.0
JComboBox Drag Problem
how to change the selected value in the jComboBox ,when selecting another jcombobox having same name
More...

All times above are in ranch (not your local) time.
The current ranch time is
Apr 16, 2024 06:23:05.