This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
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.
Joined: Feb 28, 2001
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 ]
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.