go to previous page   go to home page   go to next page

Answer:

Button-click events are delivered to the actionPerformed() method, but it always does the same thing, regardless of which button is clicked.

Picture of the Problem

Somehow, we need to write actionPerformed() so that it does something different for each button. Look again at the method:

  public void actionPerformed( Action Event evt)
  {
    getContentPane().setBackground( Color.blue );
    repaint();
  }

The picture shows the present situation. Event objects from both buttons are delivered to the same method, which changes the background to blue no matter what event it receives.

red and green buttons

We would like the ActionEvent that is delivered to actionPerformed() to say what should be done. To do this, you can associate a different command with each button using

setActionCommand(String command)

Now each button sends its command (a String) as part of the ActionEvent when it is clicked. The actionPerformed() method uses the command to see what to do.

If you don't use setActionCommand() to assign a command to a button, the command it sends will be the same as the words on the button. This is usually OK, but is awkward in large projects.

QUESTION 10:

What object(s) is setActionCommand() part of?