public class ColorDemo extends JFrame implements ActionListener
1:
2: import javax.swing.*;
3: import java.awt.*;
4: import java.awt.event.*;
5:
6: public class ColorDemo extends JFrame implements ActionListener
7: {
8: public static final int WIDTH = 400;
9: public static final int HEIGHT = 300;
10: public static final int NUMBER_OF_CHAR = 20;
11:
12: private JTextField colorName;
13:
14: public ColorDemo( )
15: {
16: setSize(WIDTH, HEIGHT);
17: WindowDestroyer listener = new WindowDestroyer( );
18: addWindowListener(listener);
19:
20: Container contentPane = getContentPane( );
21: contentPane.setBackground(Color.GRAY);
22: contentPane.setLayout(new FlowLayout( ));
23:
24: JButton showButton = new JButton("Show Color");
25: showButton.addActionListener(this);
26: contentPane.add(showButton);
27:
28: colorName = new JTextField(NUMBER_OF_CHAR);
29: contentPane.add(colorName);
30: }
31:
32: public void actionPerformed(ActionEvent e)
33: {
34: Container contentPane = getContentPane( );
35:
36: try
37: {
38: contentPane.setBackground(
39: getColor(colorName.getText()));
40: }
41: catch(UnknownColorException exception)
42: {
43: colorName.setText("Unknown Color");
44: contentPane.setBackground(Color.GRAY);
45: }
46: }
47:
48: public Color getColor(String name) throws UnknownColorException
49: {
50: if (name.equalsIgnoreCase("RED"))
51: return Color.RED;
52: else if (name.equalsIgnoreCase("WHITE"))
53: return Color.WHITE;
54: else if (name.equalsIgnoreCase("BLUE"))
55: return Color.BLUE;
56: else if (name.equalsIgnoreCase("GREEN"))
57: return Color.GREEN;
58: else
59: throw new UnknownColorException();
60: }
61: }