繁体   English   中英

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

[英]Custom JCombobox model with two toString methods

我有一个非常类似的问题,就像这个Java ComboBox不同的值名称

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

在我的情况下,我已经有一个toString()方法,我不想覆盖它。 (我需要它在其他地方)

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

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

有没有办法说“另一个toString()方法,让我们说创建JCombobox时toStringDifferent() ”?

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.

谢谢!

实际上,甚至使用toString被认为是一种很好的做法。

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);
    }
});

使用ListCellRenderer 可以在Swing教程中找到一个示例。

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

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

例:

public class        MyComboBox
    extends     JComboBox
{
  public String toString() {
    return "My toString";
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM