The API consists of a new subclass of Menu:
java.awt.PopupMenu
The main addition to this subclass is a method to invoke the popup:
public void show(Component origin, int x, int y)
This method will invoke the popup at the x,y coordinate position relative to the component parameter (the intention is that all parameters can easily be extracted from a given mouse-down event object).
add(PopupMenu popup)
remove(MenuComponent popup)
Note that a popup menu can only be owned by one component at a time.
The "origin" parameter passed into the show() method can be any component contained within the containment hierarchy defined with the popup's parent as the root (it need not be the parent itself). This is particularly useful if you need to define a single popup for an entire window; you would attach the popup menu to the frame, but could invoke it in response to a mouse-down event on any component within that frame.
The API provides a platform-independent abstraction so a program can detect a popup-menu trigger event without hard-coding platform-specific event-handling logic in the program. This is accomplished by providing the following method on java.awt.event.MouseEvent:
public boolean isPopupTrigger()
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class PopupMenuTest extends Applet implements ActionListener {
PopupMenu popup;
public void init() {
MenuItem mi;
popup = new PopupMenu("Edit");
mi = new MenuItem("Cut");
mi.addActionListener(this);
popup.add(mi);
mi = new MenuItem("Copy");
mi.addActionListener(this);
popup.add(mi);
popup.addSeparator();
mi = new MenuItem("Paste");
mi.addActionListener(this);
popup.add(mi);
add(popup); // add popup menu to applet
enableEvents(AWTEvent.MOUSE_EVENT_MASK);
resize(200, 200);
}
public void processMouseEvent(MouseEvent e) {
if (e.isPopupTrigger()) {
popup.show(e.getComponent(), e.getX(), e.getY());
}
super.processMouseEvent(e);
}
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("Cut")) {
// perform cut operation
} else if (command.equals("Copy")) {
// perform copy operation
} else if (command.equals("Paste")) {
// perform paste operation
}
}
}