Reputation: 15055
I have added a few MultiButton
s 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
Reputation: 1944
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