import java.awt.event.*; import java.awt.*; import javax.swing.*; public class MyBox extends JFrame implements ActionListener { public static final int HORIZONTAL_STRUT_SIZE = 15; public static final int VERTICAL_STRUT_SIZE = 10; public JPanel colorPanel; public MyBox() { setLocation(400,200); setSize(200,200); setTitle("MyBox"); setDefaultCloseOperation(EXIT_ON_CLOSE); colorPanel = new JPanel(); Container con = getContentPane(); con.setBackground(Color.white); con.setLayout(new BorderLayout()); con.add(colorPanel, BorderLayout.CENTER); JPanel horizontalPanel = new JPanel(); horizontalPanel.setLayout(new BoxLayout (horizontalPanel, BoxLayout.X_AXIS)); Component horizontalStrut = Box. createHorizontalStrut(HORIZONTAL_STRUT_SIZE); horizontalPanel.add(horizontalStrut); JButton red = new JButton("red"); red.addActionListener(this); horizontalPanel.add(red); Component horizontalStrut2 = Box.createHorizontalStrut (HORIZONTAL_STRUT_SIZE); horizontalPanel.add(horizontalStrut2); JButton green = new JButton("green"); green.addActionListener(this); horizontalPanel.add(green); con.add(horizontalPanel, BorderLayout.SOUTH); JPanel verticalPanel = new JPanel(); verticalPanel.setLayout(new BoxLayout (verticalPanel, BoxLayout.Y_AXIS)); Component verticalStrut = Box.createVerticalStrut(VERTICAL_STRUT_SIZE); verticalPanel.add(verticalStrut); JButton blue = new JButton("blue"); blue.addActionListener(this); verticalPanel.add(blue); Component verticalStrut2 = Box.createVerticalStrut (VERTICAL_STRUT_SIZE); verticalPanel.add(verticalStrut2); JButton yellow = new JButton("yellow"); yellow.addActionListener(this); verticalPanel.add(yellow); con.add(verticalPanel, BorderLayout.EAST); } public void actionPerformed (ActionEvent e) { Container con = getContentPane(); if(e.getActionCommand().equals("red")) { colorPanel.setBackground(Color.red); } else if(e.getActionCommand().equals("green")){ colorPanel.setBackground(Color.green); } else if(e.getActionCommand().equals("blue")){ colorPanel.setBackground(Color.blue); } else if(e.getActionCommand().equals("yellow")){ colorPanel.setBackground(Color.yellow); } else { System.out.println("ERROR"); } } public void windowClosing(WindowEvent ev){ System.exit(0); } public static void main (String [] args) { new MyBox().setVisible(true); } }