Setting JButton Commands

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:

It is one of the methods that each JButton object has. (JButtons are objects, so they have identity, state, and behavior as do all objects.)

Setting JButton Commands

Here is the program so far, but with some new blanks.

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

  // constructor for TwoButtons
  public TwoButtons()                           
  {
    super( title );
    
    redButton = new JButton("Red");
    grnButton = new JButton("Green");
    
    .setActionCommand(  );    
    .setActionCommand(  );    
    
    // register the buttonDemo frame (this)
    // as the listener for both Buttons.    
    redButton.addActionListener( this );
    grnButton.addActionListener( this );

    setLayout( new FlowLayout() ); 
    add( redButton );                      
    add( grnButton );
    setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );   
  }

  . . . .
}

QUESTION 11:

Fill in the blanks.

  1. Each button needs to have a command set for it.
  2. A command is a String.
  3. The commands must be unique.