The javax.swing package defines the JPopupMenu class, which represents a menu that you can pop up at any position within a component, but conventionally you display it at the current mouse cursor position when a particular mouse button is pressed, usually button 2. There are two constructors in the PopupMenu class: one to which you pass a String object that defines a name for the menu, and a default constructor that defines a menu without a name. If you specify a name for a pop-up menu with a statement such as
generalPopup = new PopupMenu("General");
the name you supply is primarily for identification purposes and is not always displayed when the menu is popped up: it depends on your environment. Under MS Windows, for example, it doesn't appear. This is different from a menu on a menu bar where the string you pass to the constructor is what appears on the menu bar. Don't forget to add an import statement for javax.swing.JPopupMenu.
Let's add a pop-up menu to the SketchFrame class by adding a data member of type JPopupMenu:
private JPopupMenu popup = new JPopupMenu("General"); // Window pop-up
To populate a pop-up menu with menu items, you add JMenuItem objects by passing each of them to the add() method for the JPopupMenu object. If you're using Action objects because you also want to implement toolbar buttons, you can create the JMenuItem object using a constructor that accepts a reference of type Action and then pass it to the add() method for the pop-up menu ...
With Safari, you learn the way you learn best. Get unlimited access to videos, live online training,
learning paths, books, interactive tutorials, and more.