覆蓋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 */
爲了更好地幫助更快,張貼[SSCCE](http://www.sscce.org/)。 –
「無意義」(不是)字符串是默認的toString()方法的值。確保你重寫並正確調用它。 – DSquare
我正確地調用它。還有什麼可能是一個問題嗎? – user2370759