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