5

Is there any reason why in LWUIT a Button can have its own ActionListener (via button.addActionListener) while a Command does not?

Is the only way to have a listener for a specific command is to add an ActionListener to a form and check the listener for which Command the event came from like below?

    public void startApp() {
    Display.init(this);
    f = new Form("Mixed Record");
    exit = new Command("Exit");
    start = new Command("Start");
    Button button = new Button("Button");

    f.addCommand(exit);
    f.addCommand(start);
    f.addCommand(delete);
    f.addComponent(button);

    f.addCommandListener(new ActionListener() {

        public void actionPerformed(ActionEvent ae) {
            if (ae.getCommand().equals(exit)) {
                //Do Exit command code
            } else if (ae.getCommand().equals(start)) {
                //Do Start command code
            }
        }
    });

    button.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent ae) {
            //Do button code
        }
    });

    f.show();
}

1 Answers1

6

Well, I can't tell you exactly why the people who wrote LWUIT made that decision but there are several reasons why it makes sense.

When a Form contains several Commands, they are grouped in a menu. Every time the user expands then collapses the menu, a maximum of one Command is executed. As such, the Commands are conceptually more linked to one another than Buttons are, especially since it is not uncommon to reuse Button subclasses from one Form to another.

There might also have been a concern about making the API of the LWUIT Form look a lot like the LCDUI Form in the MIDP specification.

I also like that your code shows one positive consequence of the decision:

You already have 2 unnamed inner classes (the ActionListener subclasses) in your code. If each Command had its own ActionListener, you would probably have written 3 unnamed inner classes. Developers tend to do that a lot even though, when you have spent a bit more time looking at stack traces of code that contains multiple unnamed inner classes, you will realize that it is bad practice to have more than one in each named class.

michael aubert
  • 6,836
  • 1
  • 16
  • 32
  • I see. It makes sense now.. (instead of just being annoying). Thank you for the detailed reply! – Boon McBoon Jul 26 '12 at 05:56
  • 1
    The Command is an action listener (you can subclass it and write the code in its actionPerformed method. So adding an action listener to an action listener seemed like a somewhat confusing indirection. That's why we didn't do it (original co-author of LWUIT) – Shai Almog Jul 29 '12 at 08:25