2013-08-31 44 views
0

我在我的Java應用程序中有一個JFrame窗體,它有幾個組合框應該是填充的,除了一個顯示的東西沒有意義(比如[email protected] ....),我在組合框所引用的類中做了toString方法(我對其他組合框也做了相同的操作,並且它們正常工作),但是這個組合框仍然顯示這種傳輸。 TransferObject @ 859ae5 ... 例如,MZ組合框應顯示患者姓名,所以在患者類我這樣做:使用toString方法,但組合框仍然沒有顯示值

@Override 
public String toString() { 
    return name; 
} 

但現在每次的作品,除了這個組合。問題是什麼? 謝謝

+3

爲了更好地幫助更快,張貼[SSCCE](http://www.sscce.org/)。 –

+0

「無意義」(不是)字符串是默認的toString()方法的值。確保你重寫並正確調用它。 – DSquare

+0

我正確地調用它。還有什麼可能是一個問題嗎? – user2370759

回答

2

覆蓋toString方法應該工作,但不是一個好的做法。我建議你實現一個ListCellRenderer代替,像這樣:

public class MyCellRenderer extends DefaultListCellRenderer { 
    @Override 
    public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { 
     if(value != null){ 
      if(value instanceof Patient){ 
       Patient p = (Patient) value; 
       setText(p.getName()); 
      } else { 
       setText(value.toString()); 
      } 
      if(isSelected){ 
       setBackground(...);//set background color when item is selected 
       setForeground(...);//set foreground color when item is selected 
      } else { 
       setBackground(...);//set background color when item is not selected 
       setForeground(...);//set foreground color when item is not selected 
      } 
       return this; 
     } else { 
      // do something 
      return this; 
     } 
    } 

}//end of MyClass declaration 

然後,你必須之前將項目添加到它這個類的一個實例設置爲您的JComboBox

yourJComboBox.setRenderer(new MyCellRenderer()); 
/* Now you can add items to your combo box */ 
相關問題