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