/* ButtonTest.java * * From Core Java I, Horstmann and Cornell * * March 2, 1998 */ import java.awt.*; import java.awt.event.*; import corejava.*; public class ButtonTest extends CloseableFrame implements ActionListener { public static void main( String[] args ) { ButtonTest f = new ButtonTest(); f.show(); } public ButtonTest() { setLayout( new FlowLayout() ); // Create buttons and register them Button redButton = new Button( "Red" ); add( redButton ); redButton.addActionListener( this ); Button orangeButton = new Button( "Orange" ); add( orangeButton ); orangeButton.addActionListener( this ); Button yellowButton = new Button( "Yellow" ); add( yellowButton ); yellowButton.addActionListener( this ); Button greenButton = new Button( "Green" ); add( greenButton ); greenButton.addActionListener( this ); Button blueButton = new Button( "Blue" ); add( blueButton ); blueButton.addActionListener( this ); } public void actionPerformed( ActionEvent e ) { Color c = Color.black; String arg = e.getActionCommand(); // Get color based upon button pressed if( arg.equals("Red" ) ) c = Color.red; else if( arg.equals("Orange") ) c = Color.orange; else if( arg.equals("Yellow") ) c = Color.yellow; else if( arg.equals("Green" ) ) c = Color.green; else if( arg.equals("Blue" ) ) c = Color.blue; setBackground( c ); repaint(); } }