Finish actionPerformed()

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page

Answer:

The blanks a filled in below. Each button must have a unique command, but it could be something other than the ones here.

Finish actionPerformed()

We need to add some logic so that a different action is performed for each button. An ActionEvent object contains its button's command. To get it, use the getActionCommand() method. For example, if evt refers to an ActionEvent, then evt.getActionCommand() returns the command.

Since the command is a string, use equals( String ) to compare the command to another string.

public class TwoButtons extends JFrame implements ActionListener
{
  JButton redButton ;
  JButton grnButton ;

  // constructor for TwoButtons
  public TwoButtons()                           
  {
    . . . . . . . .
    
     redButton.setActionCommand( "red" );    
     grnButton.setActionCommand( "green" );    

    setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );   
  }


  public void actionPerformed( ActionEvent evt)
  {
    if ( evt.getActionCommand().equals(  ) )
      getContentPane().setBackground(  );    
    else 
      getContentPane().setBackground( Color.green );    

    repaint(); 
  }
  . . . . . . . .
}

QUESTION 12:

Fill in the blanks in the program.