Cam Jackson
Cam Jackson

Reputation: 12294

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?

Upvotes: 1

Views: 599

Answers (2)

Cam Jackson
Cam Jackson

Reputation: 12294

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

Upvotes: 3

Atreys
Atreys

Reputation: 3761

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

Upvotes: 2

Related Questions