Java Reference
In-Depth Information
configure it with
setAction()
, and then add that to the
JPopupMenu
. Why the method isn't just
deprecated isn't clear.
Lastly, you can add a menu separator with the
addSeparator()
method.
As well as adding menu items at the end of a menu, you can insert them at specific positions or
insert a separator at a specific position:
public JMenuItem insert(Component component, int position);
public JMenuItem insert(Action action, int position);
There's no
insertSeparator()
method as there is with
JMenu
. But you can use the
add(Component component, int position)
method inherited from
Container
. If you want to
remove components, use the
remove(Component component)
method specific to
JPopupMenu
.
■
Note
Accelerators on attached
JMenuItem
objects are ignored. Mnemonics might also be ignored
depending on the currently installed look and feel.
Displaying the JPopupMenu
Unlike the
JMenu
, simply populating the pop-up menu isn't sufficient to use it. You need to
associate the pop-up menu with an appropriate component. Prior to the 5.0 release of Swing,
you needed to add event-handling code to trigger the display of the pop-up menu. Now, all you
need to do is call the
setComponentPopupMenu()
method for the Swing component you wish to
associate the pop-up menu with. When the platform-specific triggering event happens, the
pop-up menu is automatically displayed.
■
Note
Why change the way pop-up menu display is triggered? The old code was very tightly tied to mouse
events. It didn't connect well with the accessibility framework. And the same code was being added every-
where to just show the pop-up menu at the x, y coordinates of the invoker.
You simply need to create an instance of
JPopupMenu
and attach it to any component you
want to have display the pop-up menu, as follows:
JPopupMenu popupMenu = ...;
aComponent.setComponentPopupMenu(popupMenu);
The methods of
JComponent
that are important to pop-up menus are
getComponentPopupMenu()
,
setComponentPopupMenu()
,
getInheritsPopupMenu()
,
setInheritsPopupMenu()
, and
getPopupLocation()
. The
setInheritsPopupMenu()
method
accepts a
boolean
argument. When
true
, and no component pop-up menu has been directly
set for the component, the parent container will be explored for a pop-up.