簡體   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