Use PopupsTag(s): AWT


[JDK1.1]
import java.awt.*;
import java.awt.event.*;
import java.util.Hashtable;

public class PopupTest extends Frame 
    implements ActionListener, MouseListener {

  Hashtable popupTable = new Hashtable();

  public PopupTest() {
    /*
    ** regular menu
    */
    Menu m = new Menu("file");
    MenuItem item = new MenuItem("file-1");
    item.addActionListener(this);
    m.add(item);
    item = new MenuItem("file-2");
    m.add(item);
    MenuBar mb = new MenuBar();
    mb.add(m);

    setMenuBar(mb);
    setSize(100, 100);
    setLayout(new BorderLayout());

    /*
    **  label with a popup
    */
    Label l = new Label("label");
    addPopup(l, "label");
    add(l, "North");

    /*
    **  panel with popup
    */
    Panel p = new Panel();
    p.setBackground(new Color(0).red);
    addPopup(p, "Panel");
    add(p, "Center");

    /*
    **  button with popup
    */
    Button b = new Button("button");
    addPopup(b, "button");
    add(b, "South");

    addWindowListener
      (new WindowAdapter() {
          public void windowClosing(WindowEvent e) {
             System.exit(0);
             }
          }
      );

    setVisible(true);
    }

  public void actionPerformed(ActionEvent e) {
    /*
    **  handle actions related to popup
    */
    System.out.println("actionPerformed, event=" + e );
    System.out.println(" command=" + e.getActionCommand());
    System.out.println(" param=" + e.paramString());
    System.out.println(" source=" + e.getSource());
    }


  public void mouseClicked (MouseEvent e) {  }
  public void mouseEntered (MouseEvent e) {  }
  public void mouseExited (MouseEvent e) {  }
  public void mousePressed (MouseEvent e) {
    mouseAction(e);
    }

  public void mouseReleased (MouseEvent e) {
    mouseAction(e);
    }

  void mouseAction (MouseEvent e) {
    /*
    **  determine if we have to show a Popup
    */
    Component c = e.getComponent();
    if (e.isPopupTrigger()) {
       PopupMenu pm = getHash(c);
       pm.show(c, c.getSize().width/2, c.getSize().height/2);
       }
    }

  /*
  **  initialize a Popup for a particular Component
  */  

  void addPopup(Component c, String name) {
    PopupMenu pm = new PopupMenu();
    MenuItem mi1 = new MenuItem(name + "-1");
    pm.add(mi1);
    mi1.addActionListener(this);

    MenuItem mi2 = new MenuItem(name + "-2");
    pm.add(mi2);
    mi2.addActionListener(this);

    setHash(c, pm);
    c.add(pm);
    c.addMouseListener(this);
    }

  void setHash(Component c, PopupMenu p) {
    /*
    **  associate a Component with a particular Popup
    */
    popupTable.put(c, p);
    }

  PopupMenu getHash(Component c) {
    /*
    **  return a Popup associated with a particular Component
    */
    return (PopupMenu)(popupTable.get(c));
    }

  public static void main (String argv[]) {
    new PopupTest();
    }
}

blog comments powered by Disqus