首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >带有两个toString方法的自定义JCombobox模型

带有两个toString方法的自定义JCombobox模型
EN

Stack Overflow用户
提问于 2012-11-20 03:16:44
回答 3查看 2.8K关注 0票数 2

我有一个非常类似的问题,比如这个Java ComboBox Different Value to Name

我已经更改了代码,所以我将获得一个Employee-Object (我更改了我的类名,因为上面链接中的类名是Employee)。

在我的例子中,我已经有了一个toString()方法,我不想重写它。(我需要在其他地方使用它)

但是我不想在我的JCombobox中使用这个toString()方法。但它是自动的。

我不想返回任何字符串!我需要这些东西。

有没有办法在创建JCombobox时说“采用另一个toString()方法,比方说toStringDifferent()”?

代码语言:javascript
复制
this.comboEmployees = new JComboBox(new EmployeeComboboxModel(getEmployees())); 
// this will give me the toString-method's return-value of the Employee object. 
// But i want the toStringDifferent() method's result.

谢谢!

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-11-20 03:29:01

事实上,不使用toString甚至被认为是一种很好的实践。

代码语言:javascript
复制
comboEmployees.setRenderer(new DefaultListCellRenderer() {
    @Override
    public Component getListCellRendererComponent(JList list,
                                               Object value,
                                               int index,
                                               boolean isSelected,
                                               boolean cellHasFocus) {
        Employee employee = (Employee)value;
        value = employee.toStringDifferent();
        return super.getListCellRendererComponent(list, value,
                index, isSelected, csellHasFocus);
    }
});
票数 6
EN

Stack Overflow用户

发布于 2012-11-20 03:30:17

使用ListCellRenderer。可以在int the Swing tutorial中找到一个示例。

另一种方法是将对象包装在定义自己的toString()方法的对象中。

票数 1
EN

Stack Overflow用户

发布于 2012-11-20 03:29:25

您需要创建JComboBox并实现toString方法。

示例:

代码语言:javascript
复制
public class        MyComboBox
    extends     JComboBox
{
  public String toString() {
    return "My toString";
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13460555

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档