2

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

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

就我而言,我已经有一个toString()方法,我不想覆盖它。(我在其他地方需要它)

但我不想toString()在我的JCombobox. 但它会自动执行。

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

有没有办法在创建 JCombobox 时说“采取另一种toString()方法,让我们说”?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.

谢谢!

4

3 回答 3

6

事实上,使用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);
    }
});
于 2012-11-19T19:29:00.937 回答
1

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

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

于 2012-11-19T19:30:17.097 回答
0

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

例子:

public class        MyComboBox
    extends     JComboBox
{
  public String toString() {
    return "My toString";
    }
}
于 2012-11-19T19:29:25.090 回答