Pop-Up Menus
One of Swing’s nifty components is JPopupMenu, a context
menu that appears at the mouse location when you press the appropriate
mouse button or keystroke. (On a two-button mouse, clicking the right
mouse button invokes a pop-up menu. On a single-button Mac, you
Command-click.) Which button you press depends on the platform you’re
using; fortunately, from the code’s point of view you don’t have to
care—Swing figures it out for you.
The care and feeding of JPopupMenu is basically the same as any other
menu. You use a different constructor—JPopupMenu()—to create it, but otherwise, you
build a menu and add elements to it the same way. The big difference is
that you don’t attach it to a JMenuBar.
Instead, just pop up the menu whenever and wherever you need it. Prior to
Java 5.0, this process is a little cumbersome; you have to register to
receive the appropriate mouse events, check them to see if they are the
pop-up trigger and then pop the menu manually. With Java 5.0, the process
is simplified by having components manage their own pop-up menus.
First, we’ll show an example of explicit pop-up handling. The
following example, PopupColorMenu,
contains three buttons. You can use a JPopupMenu to set the color of each button or
the background frame itself, depending on where you click the
mouse.
//file: PopUpColorMenu.javaimportjava.awt.*;importjava.awt.event.*;importjavax.swing.*;publicclassPopUpColorMenuimplementsActionListener{ComponentselectedComponent;public ...