Source of PanelDemo.java


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