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

Answer:

The layout manager has been added.

Setting the Layout Manager

FlowLayout() will position the two buttons nicely within the area of the frame.

import java.awt.*; 
import java.awt.event.*;
import javax.swing.*; 

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");

    // choose the layout manager
    setLayout( new FlowLayout() );

    add( redButton );                      
    add( grnButton );                      

    setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );   
  }
  
  . . . . more code will go here . . . . 

  public static void main ( String[] args )
  {
    TwoButtons demo  = new TwoButtons( "Click a Button") ;

    demo.setSize( 200, 150 );     
    demo.setVisible( true );      

  }
}

An action listener needs to be registered for the two buttons. There are various ways that this could be done, but let us use one listener that will listen to both of the buttons. The listener object will be the same object as the container, the object of type TwoButtons.

QUESTION 8:

What is the name of the method that an action listener must implement? Where should it go in the above program?