Source of ColorDemoApplet.java


  1: //ColorDemoApplet.java
  2: 
  3: import javax.swing.JApplet;
  4: import javax.swing.JButton;
  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 ColorDemoApplet
 14:     extends JApplet
 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 void init()
 24:     {
 25:         Container contentPane = getContentPane();
 26:         contentPane.setBackground(Color.GRAY);
 27:         contentPane.setLayout(new FlowLayout());
 28: 
 29:         JButton showButton = new JButton("Show Color");
 30:         showButton.addActionListener(this);
 31:         contentPane.add(showButton);
 32: 
 33:         colorName = new JTextField(NUMBER_OF_CHAR);
 34:         contentPane.add(colorName);
 35:     }
 36: 
 37:     public void actionPerformed
 38:     (
 39:         ActionEvent e
 40:     )
 41:     {
 42:         Container contentPane = getContentPane();
 43: 
 44:         try
 45:         {
 46:             contentPane.setBackground(getColor(colorName.getText()));
 47:         }
 48:         catch (UnknownColorException exception)
 49:         {
 50:             colorName.setText("Unknown Color");
 51:             contentPane.setBackground(Color.GRAY);
 52:         }
 53:     }
 54: 
 55:     public Color getColor
 56:     (
 57:         String name
 58:     ) throws UnknownColorException
 59:     {
 60:         if (name.equalsIgnoreCase("RED"))
 61:             return Color.RED;
 62:         else if (name.equalsIgnoreCase("WHITE"))
 63:             return Color.WHITE;
 64:         else if (name.equalsIgnoreCase("BLUE"))
 65:             return Color.BLUE;
 66:         else if (name.equalsIgnoreCase("GREEN"))
 67:             return Color.GREEN;
 68:         else
 69:             throw new UnknownColorException();
 70:     }
 71: }