覆盖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 */