【问题标题】:Using toString method but the combo box still doesn't show values使用 toString 方法,但组合框仍然不显示值
【发布时间】:2013-08-31 12:08:44
【问题描述】:

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

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

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

【问题讨论】:

  • 如需尽快获得更好的帮助,请发帖SSCCE
  • 那个“无意义”(不是)字符串是默认的 toString() 方法的值。确保您正在覆盖并正确调用它。
  • 我说得对。这里还有什么问题?
  • @user2370759 显示整个班级。
  • 我无法发布整个课程,因为我还没有足够的消息。但是我使用 toString() 的类只包含构造函数、getter 和 setter。

标签: java swing tostring


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-23
    • 1970-01-01
    • 2018-06-26
    • 2015-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多