import javax.swing.*; import java.awt.*; //Color class import java.awt.event.*; //event listener interface public class Ex31_ColorWindow extends JFrame { private JLabel messageLabel; //message private JButton redButton; private JButton blueButton; private JButton yellowButton; private JPanel panel; //panle to hold components private final int WINDOW_WIDTH = 200; private final int WINDOW_HEIGHT = 125; //constructor public Ex31_ColorWindow() { setTitle("Colors"); setSize (WINDOW_WIDTH, WINDOW_HEIGHT); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); messageLabel = new JLabel("Click a button to select a color."); redButton = new JButton("Red"); blueButton = new JButton("Blue"); yellowButton = new JButton("Yellow"); redButton.addActionListener(new RedButtonListener()); blueButton.addActionListener(new BlueButtonListener()); yellowButton.addActionListener(new YellowButtonListener()); panel = new JPanel(); panel.add(messageLabel); panel.add(redButton); panel.add(blueButton); panel.add(yellowButton); add(panel); setVisible(true); } private class RedButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { panel.setBackground(Color.RED); messageLabel.setForeground(Color.BLUE); messageLabel.setText("Blue and red do not go well."); } } private class BlueButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { panel.setBackground(Color.BLUE); messageLabel.setForeground(Color.YELLOW); messageLabel.setText("Blue and yellow? Perhaps."); } } private class YellowButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { panel.setBackground(Color.YELLOW); messageLabel.setForeground(Color.BLACK); messageLabel.setText("Yellow and black? Maybe."); } } }