import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

/** Simple demo of pop-up menus. 
 *
 *  Taken from Core Web Programming from 
 *  Prentice Hall and Sun Microsystems Press,
 *  http://www.corewebprogramming.com/.
 *  &copy; 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

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 MenuItems. */
                              
  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/98/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);
  }
}
