为什么不在我传递给JComboBox的对象上调用toString()?

时间:2011-08-05 02:14:32

标签: java python swing jython tostring

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

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方法以提供要显示的字符串。

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

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

然后再说:

pickedId = combo.getSelectedItem().id

但是,我的组合中显示的文字就像<command.Choice object at 0x2>一样,我print中的Choice.toString()语句从未发生过。{/ p>

有什么想法吗?

2 个答案:

答案 0 :(得分:3)

发现它!在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

答案 1 :(得分:2)

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

相关问题