10.9 PopupMenuThe PopupMenu class is new to Java 1.1; it allows you to associate context-sensitive menus with Java components. To associate a pop-up menu with a component, create the menu, and add it to the component using the add(PopupMenu) method, which all components inherit from the Component class. In principle, any GUI object can have a pop-up menu. In practice, there are a few exceptions. If the component's peer has its own pop-up menu (i.e., a pop-up menu provided by the run-time platform), that pop-up menu effectively overrides the pop-up menu provided by Java. For example, under Windows NT/95, a TextArea has a pop-up menu provided by the Windows NT/95 platforms. Java can't override this menu; although you can add a pop-up menu to a TextArea, you can't display that menu under Windows NT/95 with the usual mouse sequence. PopupMenu MethodsConstructors
Example 10.3 is a simple applet that raises a pop-up menu if the user clicks the appropriate mouse button anywhere within the applet. Although the program could use the 1.0 event model, under the 1.0 model, it is impossible to tell which mouse event is appropriate to display the pop-up menu. Example 10.3: Using a PopupMenu
// Java 1.1 only import java.awt.*; import java.applet.*; import java.awt.event.*; public class PopupTest extends Applet implements ActionListener { PopupMenu popup; public void init() { MenuItem mi; popup = new PopupMenu("Title Goes Here"); popup.add(mi = new MenuItem ("Undo")); mi.addActionListener (this); popup.addSeparator(); popup.add(mi = new MenuItem("Cut")).setEnabled(false); mi.addActionListener (this); popup.add(mi = new MenuItem("Copy")).setEnabled(false); mi.addActionListener (this); popup.add(mi = new MenuItem ("Paste")); mi.addActionListener (this); popup.add(mi = new MenuItem("Delete")).setEnabled(false); mi.addActionListener (this); popup.addSeparator(); popup.add(mi = new MenuItem ("Select All")); mi.addActionListener (this); add (popup); resize(200, 200); enableEvents (AWTEvent.MOUSE_EVENT_MASK); } protected void processMouseEvent (MouseEvent e) { if (e.isPopupTrigger()) popup.show(e.getComponent(), e.getX(), e.getY()); super.processMouseEvent (e); } public void actionPerformed(ActionEvent e) { System.out.println (e); } } |
|