简体   繁体   中英

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

您应该在python类中重写__str__(self)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM