Java Swing:扩展 DefaultComboBoxModel 并覆盖方法 [英] Java Swing: Extend DefaultComboBoxModel and override methods

查看:25
本文介绍了Java Swing:扩展 DefaultComboBoxModel 并覆盖方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 DefaultComboBoxModelJComboBox 中显示客户列表.该列表目前仅显示他们的名字.我还希望对 DefaultComboBoxModel 中的每个客户都有一个引用,以便在选择名称时,它还保存对真实客户对象的引用.

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.

为了实现这一点,我怀疑我必须扩展 DefaultComboBoxModel 并可能覆盖 addElement() 方法?或者我可以添加一个新方法来存储我对客户的引用吗?如果是这样,我是否必须查看 DefaultComboBoxModel 的源代码以查看它如何存储元素?对不起,如果这个问题令人困惑,但我不知道如何正确地做到这一点.感谢阅读.

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.

推荐答案

如果您在 Customer 对象中重写 toString() 以返回您想要在 JComboBox 中显示的任何内容,它将正常工作.如果您将 toString 用于其他目的,您需要覆盖模型或渲染器以使用 Customer 对象中的正确字段.

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.

-更新汤姆的建议-创建一个新对象 CustomerView,它包装真实的客户对象,因此可以提供对它的引用,但它也覆盖 toString() 以返回客户的姓名.

-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.

这篇关于Java Swing:扩展 DefaultComboBoxModel 并覆盖方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆