tags:

views:

305

answers:

1

I am using the DefaultComboBoxModel to display a list of customers in a ComboBox. The list currently displays their name only. I would also like to have a reference to each customer within the DefaultComboBoxModel so that when a name is selected, it also holds the reference to the real customer object.

To achieve this, I suspect I have to extend the DefaultComboBoxModel and possibly override the addElement method? Or can I just add a new method that can also store my references to customers? If so, do I have to look at the source code for DefaultComboBoxModel to see how it stores the elements? Sorry if this question is confusing but I can't figure out how to do it the right way. Thanks for reading.

+4  A: 

If you in your Customer object override toString() to return whatever you want presented in the JComboBox it will work just fine. If you are using toString for other purposes you need to override the model or renderer to use the correct fields from the Customer object.

-Update Tom's Suggestion- Create a new object CustomerView which wraps the real customer objects and can thus provide a reference to it but which also overrides toString() to return the name of the customer.

willcodejavaforfood
Rather than change the model or (more so) the renderer if changing `Customer.toString` is inappropriate, add a `CustomerComboView` (or similar name) that has an appropriate display representation of the `Customer` object (with methods `toString` and `getCustomer`/`customer`).
Tom Hawtin - tackline
@Tom Hawtin - Thank you that is obviously a lot better
willcodejavaforfood
Excellent suggestions, thank you both!
Johan