开发者

Why isn't swing calling toString() on the objects I pass to a JComboBox?

I have this class to represent choices in a combobox:

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

I have an array of Choice objects, and I want to show the label values in a JComboBox, but be able to retrieve the id later, after the array has gone out of scope.

On the subject of JComboBox renderers, the Java Swing tutorial says,

The default renderer knows how to render strings and icons. If you put other objects in a combo box, the default renderer calls the toString method to provide a string to display.

So, given that I've added a toString() method to my Choice class, I should just be able to do this:

开发者_运维知识库
choices = [Choice(1, 'foo'), Choice(3, 'bar'), Choice(5, 'baz')]
combo = JComboBox(choices)

and then later:

pickedId = combo.getSelectedItem().id

However, the text that shows in my combo is like <command.Choice object at 0x2>, and that print statement that I've put into Choice.toString() never happens.

Any ideas?


Found it! On the back of Atrey's answer and JimN's comment, I found out that Python's equivalent to toString() is actually __repr__.

So my class now looks like:

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

    def __repr__(self):
        return self.label


You should override __str__(self) in your python class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜