Using Command class to invoke commands

The usage of Command class is very simple. You give the name of the command in the constructor and add it to the menu. There are several ways to handle the invoking of a Command.

Override the actionPerformed method in Command class:

Command cmd = new Command("Hello") {
    public void actionPerformed(ActionEvent evt) {
        //do something
    }
};

Override the Form's actionPerformed method:

Form f = new Form("form") {
    protected void actionCommand(Command cmd) {
        //handle all commands that are added to Form
    }
};

Add ActionListener by using the Form's addCommandListener-method. The main thing to note here is that if you have several CommandListeners, you need to call ActionEvent.consume if you do not want the event to go to other CommandListeners:

f.addCommandListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
        // use ae.getCommand() to get the command
    }
});

There is really not that much difference between the solutions. The first one is useful if you want to transfer the same Command between Forms and do not want to create separate ActionListener or override the Form's actionCommand method. The second one is generally useful when you want to handle all the commands in same place. The third solution is useful when you want to listen the Command with many listeners and want to limit which listeners get the event, or you want to get some extra information about the event, like the x,y coordinate or key event.