Java Swing: Extending DefaultComboBoxModel and Overriding Methods

I am using DefaultComboBoxModel to display a list of clients in JComboBox . Currently, the list displays only their name. I would also like to have a link to each client in DefaultComboBoxModel , so that when you select a name, it also contains a link to the object of the real client.

To achieve this, I suspect that I need to extend DefaultComboBoxModel and possibly override the addElement() method? Or can I just add a new method that can also store my client links? If so, do I need to look for the source code for DefaultComboBoxModel to find out how it stores the elements? Sorry if this question is confusing, but I cannot figure out how to do this correctly. Thanks for reading.

+7
java swing
source share
1 answer

If you override toString () in the Customer object to return everything you want to represent in the JComboBox, it will work fine. If you use toString for other purposes, you need to override the model or rendering in order to use the correct fields in the Customer object.

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

+6
source share

All Articles