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