Source of ColorDemoApplet.java


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