noelicus
noelicus

Reputation: 15055

Why is the ActionEvent component the wrong type?

I have added a few MultiButtons dynamically and each has a new ActionListener. When the ActionListener is called the Component is of type Button and not the actual MultiButton object (i.e. the cast to MultiButton causes a ClassCastException cannot cast Button to MultiButton).

Is there a way to get the MultiButton instead? Or have I done something silly?

Code:

Container cBob = findContainerBob(f);

cBob.removeAll();

for (String str : things) {
    MultiButton mb = new MultiButton();
    mb.setTextLine1(str);

    mb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            MultiButton clickedMb = (MultiButton)evt.getComponent(); // Throws exception                
        });         

    cBob.addComponent(mb);
}

Upvotes: 1

Views: 103

Answers (1)

Sebastian Höffner
Sebastian Höffner

Reputation: 1944

http://code.google.com/p/codenameone/source/browse/trunk/CodenameOne/src/com/codename1/components/MultiButton.java?r=317

If you look at the source of the MultiButton in codenameone, you will see this method:

/**
 * Adds an action listener
 * 
 * @param al the action listener
 */
public void addActionListener(ActionListener al) {
    emblem.addActionListener(al);
}

emblem is a member and declared as Button:

private Button emblem = new Button();

So the Component you get with your evt.getComponent() call is indeed a button.

Update: To get your button as a MultiButton you should use:

MultiButton multiButton = (MultiButton) evt.getComponent().getParent().getLeadParent();

Upvotes: 2

Related Questions