我的 Java 应用程序中有一个 JFrame 表单,它有几个组合框,它们按应有的方式填充,除了一个显示没有意义的内容(例如 Transfer.TransferObject@859ae5....),我做了组合框引用的类中的 toString 方法(我对其他组合框做了同样的事情,它们正常工作),但是这个组合仍然显示此传输。TransferObject@859ae5... 例如,mz 组合框应显示患者姓名,因此在患者类中我执行以下操作:
@Override
public String toString() {
return name;
}
但它每次都有效,除了现在这个组合。问题是什么? 谢谢
最佳答案
重写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 添加项目之前将此类的一个实例设置为 JComboBox:
yourJComboBox.setRenderer(new MyCellRenderer());
/* Now you can add items to your combo box */
关于java - 使用 toString 方法但组合框仍然不显示值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18547974/