You've already encountered the Choice
class that
implements a popup menu component. Choices are fixed in a
particular location.
The PopupMenu
class, on the other hand, is
activated when the user holds the right mouse button or otherwise
indicates that they want to pop up a menu. Typically this is used
for context sensitive menus.
java.awt.PopupMenu
is a subclass of of
java.awt.Menu
. For the most part you use it just like you
use a regular menu. Items are added to it with the
add(MenuItem mi)
method, and user selections are responded
to by installing an ActionListener on the MenuItem
.
For example, to build a popup menu with a number of URLs you might
do this:
PopupMenu pm = new PopupMenu();
MenuItem mi = new MenuItem("http://java.sun.com/");
mi.addActionListener(URLActionListener);
pm.add(mi);
mi = new MenuItem("http://home.netscape.com/");
mi.addActionListener(URLActionListener);
pm.add(mi);
mi = new MenuItem("http://www.cafeaulait.org/course/");
mi.addActionListener(URLActionListener);
pm.add(mi);
MenuItem mi = new MenuItem("http://www.yahoo.com/");
mi.addActionListener(URLActionListener);
pm.add(mi);
However PopupMenu
s don't belong to any particular
MenuBar
. Instead they're added to a component. For
example, given a Frame f
, you would install the
PopupMenu pm
in the frame by passing it to the frame's
add()
method, like so:
f.add(pm);
(Is this the same add()
method used to add components
to a frame?)
The exact trigger for popping up the menu is platform dependent.
For example, on Windows a PopupMenu
is triggered on
right mouse button up. However, in Motif a PopupMenu
is triggered on right mouse button down. Regardless of the exact
sequence of events leading to a menu popping up, when the user
makes a selection, when a MenuItem
is selected an
ActionEvent
is fired to any listeners registered for
that item.
A PopupMenu
can be deinstalled from a component by
passing it to the component's remove()
method like
this:
f.remove(pm);
No more than one PopupMenu
can be installed in any given component.
If a PopupMenu
is installed in a container, then triggers over the
container's components will also trigger the popup, provided the
contained component has no popup of its own.