public class BoxClassDemo extends JFrame implements ActionListener
1: import javax.swing.*;
2: import java.awt.*;
3: import java.awt.event.*;
4:
5: /**
6: Simple demonstration of Box container class and the use of struts
7: to separate components (in this case buttons). For an alternative
8: implementation see BoxLayoutDemo in Display 13.10.
9: */
10: public class BoxClassDemo extends JFrame implements ActionListener
11: {
12: public static final int WIDTH = 300;
13: public static final int HEIGHT = 200;
14: public static final int HORIZONTAL_STRUT_SIZE = 15;
15: public static final int VERTICAL_STRUT_SIZE = 10;
16:
17: private JPanel colorPanel;
18:
19: public BoxClassDemo( )
20: {
21: setSize(WIDTH, HEIGHT);
22: addWindowListener(new WindowDestroyer( ));
23: setTitle("Box Demonstration");
24: Container content = getContentPane( );
25: content.setLayout(new BorderLayout( ));
26:
27: colorPanel = new JPanel( );
28: colorPanel.setBackground(Color.BLUE);
29: content.add(colorPanel, BorderLayout.CENTER);
30:
31: //Horizontal buttons at bottom of frame:
32: Box horizontalBox = Box.createHorizontalBox( );
33:
34: Component horizontalStrut =
35: Box.createHorizontalStrut(HORIZONTAL_STRUT_SIZE);
36: horizontalBox.add(horizontalStrut);
37:
38: JButton hStopButton = new JButton("Red");
39: hStopButton.addActionListener(this);
40: horizontalBox.add(hStopButton);
41: Component horizontalStrut2 =
42: Box.createHorizontalStrut(HORIZONTAL_STRUT_SIZE);
43: horizontalBox.add(horizontalStrut2);
44:
45: JButton hGoButton = new JButton("Green");
46: hGoButton.addActionListener(this);
47: horizontalBox.add(hGoButton);
48:
49: content.add(horizontalBox, BorderLayout.SOUTH);
50:
51: //Vertical buttons on right side of frame:
52: Box verticalBox = Box.createVerticalBox( );
53:
54: Component verticalStrut = Box.createVerticalStrut(VERTICAL_STRUT_SIZE);
55: verticalBox.add(verticalStrut);
56:
57: JButton vStopButton = new JButton("Red");
58: vStopButton.addActionListener(this);
59: verticalBox.add(vStopButton);
60:
61: Component verticalStrut2 = Box.createVerticalStrut(VERTICAL_STRUT_SIZE);
62: verticalBox.add(verticalStrut2);
63:
64: JButton vGoButton = new JButton("Green");
65: vGoButton.addActionListener(this);
66: verticalBox.add(vGoButton);
67:
68: content.add(verticalBox, BorderLayout.EAST);
69: }
70:
71: public void actionPerformed(ActionEvent e)
72: {
73: if (e.getActionCommand( ).equals("Red"))
74: colorPanel.setBackground(Color.RED);
75: else if (e.getActionCommand( ).equals("Green"))
76: colorPanel.setBackground(Color.GREEN);
77: else
78: System.out.println("Error in button interface.");
79: }
80:
81: public static void main(String[] args)
82: {
83: BoxClassDemo gui = new BoxClassDemo( );
84: gui.setVisible(true);
85: }
86: }