2012-11-19 43 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()方法的對象中。