Source of ColorDemoApplet.java


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