0

我的 Java 应用程序中有一个 JFrame 表单,它有几个按应有的方式填充的组合框,除了一个显示没有意义的东西(如 transfer.TransferObject@859ae5 ....),我做了 toString 方法组合框所指的类(我对其他组合框做了同样的操作,它们正常工作),但是这个组合仍然显示这个 transfer.TransferObject@859ae5 ... 例如,mz 组合框应该显示名称患者,所以在患者类中我这样做:

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

但它每次都有效,除了现在这个组合。问题是什么?谢谢

4

1 回答 1

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 */
于 2013-08-31T12:33:32.693 回答