【问题标题】:Why isn't swing calling toString() on the objects I pass to a JComboBox?为什么不对我传递给 JComboBox 的对象调用 toString()?
【发布时间】:2011-08-05 02:14:31
【问题描述】:

我有这个类来表示组合框中的选择:

class Choice(object):
    def __init__(self, id, label):
        self.id = id
        self.label = label

    def toString(self):
        print "in Choice.toString" #for debugging
        return self.label

我有一个 Choice 对象数组,我想在 JComboBox 中显示标签值,但以后可以在数组超出范围后检索 id。

关于 JComboBox 渲染器的主题,the Java Swing tutorial says

默认渲染器知道如何渲染字符串和图标。如果将其他对象放在组合框中,默认渲染器会调用 toString 方法提供要显示的字符串。

所以,鉴于我已经在我的 Choice 类中添加了一个 toString() 方法,我应该能够做到这一点:

choices = [Choice(1, 'foo'), Choice(3, 'bar'), Choice(5, 'baz')]
combo = JComboBox(choices)

然后:

pickedId = combo.getSelectedItem().id

但是,我的组合中显示的文本类似于 <command.Choice object at 0x2>,而我放入 Choice.toString()print 语句从未发生过。

有什么想法吗?

【问题讨论】:

  • 我不熟悉 python/jython,但您创建的 toString() 方法可能没有扩展“void Object.toString()”(可能签名不匹配)。尝试使用 javap 检查编译的类。

标签: java python swing jython tostring


【解决方案1】:

找到了!在 Atrey 的回答和 JimN 的评论的后面,我发现 Python 相当于 toString() 实际上是 __repr__

所以我的班级现在看起来像:

class Choice(object):
    def __init__(self, id, label):
        self.id = id
        self.label = label

    def __repr__(self):
        return self.label

【讨论】:

  • 这很有趣,因为__repr__ 应该返回一个python 代码来重新创建对象,而__str__ 应该返回一个更自然的对象表示。很好的发现!
  • @Atreys 的“可以重新创建对象的返回码”的想法已经被抹黑了一段时间;在很多情况下,这被证明是一个坏主意(或至少是不可行的)。
【解决方案2】:

你应该在你的 python 类中覆盖__str__(self)

【讨论】:

  • (假设。toString 用于 Java。__str__ 用于 python)
  • 想通了。原来等价于toString 的不是__str__ 而是__repr__。感谢您为我指明正确的方向! :)
猜你喜欢
  • 1970-01-01
  • 2013-05-18
  • 2018-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多