A good answer might be:The only problem is coordinating the command the button sends with what the listener does. | |
Corrected |
import java.awt.*;
import java.awt.event.*;
public class TwoButtons extends Frame implements ActionListener
{
Button redButton = new Button("Red");
Button grnButton = new Button("Green");
TwoButtons() // constructor for TwoButtons
{
setLayout( new FlowLayout() ); // choose the layout manager
redButton.addActionListener( this ); // the buttonDemo object is
grnButton.addActionListener( this ); // the listener for each Button.
redButton.setActionCommand( "red" ); // set the red button's command
grnButton.setActionCommand( "green" ); // set the green button's command
add( redButton ); // add the buttons to the container
add( grnButton );
}
public void actionPerformed( ActionEvent evt)
{
// check which command has been sent
if ( evt.getActionCommand().equals( "red" ) )
setBackground( Color.red );
else
setBackground( Color.green );
repaint(); // ask the system to paint the screen.
}
public static void main ( String[] args )
{
TwoButtons demo = new TwoButtons() ;
WindowQuitter wquit = new WindowQuitter();
demo.addWindowListener( wquit );
demo.setSize( 200, 150 );
demo.setVisible( true );
}
}
class WindowQuitter extends WindowAdapter
{
public void windowClosing( WindowEvent e )
{
System.exit( 0 ); // what to do for this event--exit the program
}
}
|
Of course, you will copy it and run it. It is the basis of the programming exercises for this chapter.
When the program is running, does it matter in which order the buttons are clicked?
Click Here after you have answered the question