import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

// This appears in Core Web Programming from
// Prentice Hall Publishers, and may be freely used
// or adapted. 1997 Marty Hall, hall@apl.jhu.edu.

/** Simple demo of popup menus in Java 1.1 */

public class ColorPopupMenu extends Applet
                            implements ActionListener {
 private String[] colorNames =
   { "White", "Light Gray", "Gray",
     "Dark Gray", "Black" };
  private Color[] colors =
    { Color.white, Color.lightGray, Color.gray,
      Color.darkGray, Color.black };
  private PopupMenu menu;

  /** Create PopupMenu and add MenuItem's */
                              
  public void init() {
    setBackground(Color.gray);
    menu = new PopupMenu("Background Color");
    enableEvents(AWTEvent.MOUSE_EVENT_MASK);
    MenuItem colorName;
    for(int i=0; i<colorNames.length; i++) {
      colorName = new MenuItem(colorNames[i]);
      menu.add(colorName);
      colorName.addActionListener(this);
      menu.addSeparator();
    }
    add(menu);
  }

  /** Don't use a MouseListener, since in Win95/NT
   *  you have to check isPopupTrigger in
   *  mouseReleased, but do it in mousePressed in
   *  Solaris (boo!).
   */
  public void processMouseEvent(MouseEvent event) {
    if (event.isPopupTrigger())
      menu.show(event.getComponent(),
                event.getX(), event.getY());
    super.processMouseEvent(event);
  }
  
  public void actionPerformed(ActionEvent event) {
    setBackground(colorNamed(event.getActionCommand()));
    repaint();
  }

  private Color colorNamed(String colorName) {
    for(int i=0; i<colorNames.length; i++)
      if(colorNames[i].equals(colorName))
        return(colors[i]);
    return(Color.white);
  }
}

