Source of ButtonDemo.java


  1: 
  2: import javax.swing.JButton;
  3: import javax.swing.JFrame;
  4: import java.awt.Color;
  5: import java.awt.Container;
  6: import java.awt.FlowLayout;
  7: import java.awt.event.ActionEvent;
  8: import java.awt.event.ActionListener;
  9: 
 10: /**
 11:  Simple demonstration of putting buttons in a JFrame.
 12: */
 13: public class ButtonDemo extends JFrame implements ActionListener
 14: {
 15:     public static final int WIDTH = 300;
 16:     public static final int HEIGHT = 200;
 17: 
 18:     public ButtonDemo( )
 19:     {
 20:         setSize(WIDTH, HEIGHT);
 21: 
 22:         addWindowListener(new WindowDestroyer( ));
 23:         setTitle("Button Demo");
 24:         Container contentPane = getContentPane( );
 25:         contentPane.setBackground(Color.BLUE);
 26: 
 27:         contentPane.setLayout(new FlowLayout( ));
 28: 
 29:         JButton stopButton = new JButton("Red");
 30:         stopButton.addActionListener(this);
 31:         contentPane.add(stopButton);
 32: 
 33:         JButton goButton = new JButton("Green");
 34:         goButton.addActionListener(this);
 35:         contentPane.add(goButton);
 36:     }
 37: 
 38:     public void actionPerformed(ActionEvent e)
 39:     {
 40:        Container contentPane = getContentPane( );
 41: 
 42:        if (e.getActionCommand( ).equals("Red"))
 43:            contentPane.setBackground(Color.RED);
 44:        else if (e.getActionCommand( ).equals("Green"))
 45:            contentPane.setBackground(Color.GREEN);
 46:        else
 47:            System.out.println("Error in button interface.");
 48:     }
 49: 
 50:     /**
 51:      Creates and displays a window of the class ButtonDemo.
 52:     */
 53:     public static void main(String[] args)
 54:     {
 55:         ButtonDemo buttonGui = new ButtonDemo( );
 56:         buttonGui.setVisible(true);
 57:     }
 58: }
 59: