Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Swing: Extend DefaultComboBoxModel and override methods

Tags:

java

swing

I am using the DefaultComboBoxModel to display a list of customers in a JComboBox. 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.

like image 329
Johan Avatar asked Jan 11 '10 13:01

Johan


1 Answers

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.

like image 174
willcodejavaforfood Avatar answered Oct 19 '22 06:10

willcodejavaforfood