2012-11-19 46 views
2

定制JComboBox的模型我有这样一个Java ComboBox Different Value to Name两种方法的toString

我已经改变了代码一个非常类似的问题,所以我会得到一个Employee -object(我改变了我的类名,因为在类名上面的链接是Employee)。

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

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

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

在创建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. 

谢谢!

回答

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

对我很好。 不知何故我得到一个空指针(我认为第一个或最后一个条目)。我做了一个if(employee!= null)引发了“value = employee.toStringDifferent();”它的工作。 – eav

+0

@Joop:“事实上,它甚至被认为是不使用toString的好习惯。”谁说的? – splungebob

+1

@splungebpb我曾经用'toString'给出了一个答案,并得到了批评性评论,就这么说。我不认为这是一个铁律,并会使用最合适的。但我承认写一个toString只是为了显示在JComboBox中也不是很好的风格。 –

0

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

实施例:

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

我想你可能误解了这个问题;) – MadProgrammer

1

使用ListCellRenderer。一个例子可以发现int the Swing tutorial

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