Java Reference
In-Depth Information
Only one allows you to initialize the title for the menu, if desired. What happens with the
title depends on the installed look and feel. The currently installed look and feel may ignore
the title.
Adding Menu Items to a JPopupMenu
As with a JMenu , once you have a JPopupMenu , you need to add menu item objects to it; other-
wise, the menu will be empty. There are three JPopupMenu methods for adding menu items and
one for adding a separator:
public JMenuItem add(JMenuItem menuItem);
public JMenuItem add(String label);
public JMenuItem add(Action action);
public void addSeparator();
In addition, an add() method is inherited from Container for adding regular AWT
components:
public Component add(Component component);
Note It generally isn't wise to mix lightweight Swing components with heavyweight AWT components.
However, because pop-up menus are more apt to be on top, it's less of an issue in this case.
The natural way of adding menu items is with the first add() method. You create the menu
item independently of the pop-up menu, including defining its behavior, and then you attach it
to the menu. With the second variety of add() , you must attach an event handler to the menu
item returned from the method; otherwise, the menu choice won't respond when selected. The
following source demonstrates the two approaches. Which you use depends entirely on your
preference. A visual programming environment like JBuilder will use the first. Because the
first approach is inherently less complex, most, if not all, programmers should also use
the first approach.
JPopupMenu popupenu = new JPopupMenu();
ActionListener anActionListener = ...;
// The first way
JMenuItem firstItem = new JMenuItem("Hello");
firstItem.addActionListener(anActionListener);
popupMenu.add(firstItem);
// The second way
JMenuItem secondItem = popupMenu.add("World");
secondItem.addActionListener(anActionListener);
Using an Action to create a menu item works the same with JPopupMenu as it does with
JMenu . However, according to the Javadoc for the JPopupMenu class, using the Action variety of
the add() method is discouraged. Instead, pass the Action to the constructor for JMenuItem , or
 
Search WWH ::




Custom Search