CS396N - Web Programming
Spring 2002
Chapter 13 - AWT Components Continued

The TextField Class


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

public class TextFields extends Applet {
  public void init() {
    add(new TextField()); // Four Constructors
    add(new TextField(30));
    add(new TextField("Initial String"));
    add(new TextField("Initial", 30));
  }
}

Pop-Up Menus


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

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);
  }

  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);
  }
}