将对象添加到JComboBox,但显示一个字符串而不覆盖该对象的.toString()方法 [英] Add an object to a JComboBox but show a string without overriding the object's .toString() method

查看:62
本文介绍了将对象添加到JComboBox,但显示一个字符串而不覆盖该对象的.toString()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用的对象类已经覆盖了它的.toString()方法,并为其命名.但是我在JComboBox中使用相同的对象,因此我需要显示另一个String.有没有办法做到这一点?

The object class that I am working with already has its .toString() method overridden, giving its name. But I am using same object in a JComboBox and I need to display another String. Is there a way to accomplish this?

推荐答案

您敢打赌!您要做的就是为您的JComboBox提供一个自定义的单元格渲染器.

You bet there is! What you want to do is to give your JComboBox a custom cell renderer.

为此,您可以扩展DefaultListCellRenderer以确保覆盖其getListCellRendererComponent(...)方法.完成此操作后,您将在JComboBox上调用setRenderer(...),并传入新类的对象.

To do this, you could extending DefaultListCellRenderer making sure to override its getListCellRendererComponent(...) method. Once you've done this, you would call setRenderer(...) on your JComboBox, passing in an object of your new class.

有关更多信息,请确保查看 JComboBox教程的渲染器部分.

For more on this, please be sure to check out the renderer section of the JComboBox tutorial.

这篇关于将对象添加到JComboBox,但显示一个字符串而不覆盖该对象的.toString()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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