Java Reference
In-Depth Information
How It Works
This last piece is relatively trivial. The additional menu is added to the menu bar just like the other menus.
The menu item is a JMenuItem object rather than an Action object and the actionPerformed() method
is called when the Choose font . . . menu item is clicked. This sets the top-left corner of the dialog win-
dow one-third of the way in from the top and left sides of the application window. It then calls setVis-
ible() for the dialog object to display it.
POP-UP MENUS
The javax.swing package defines the JPopupMenu class, which represents a menu that you can pop up at
any position within a component. Conventionally you display a pop-up menu at the current mouse curs-
or 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 Microsoft 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 SketcherFrame 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 imple-
ment 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 object. You can also pass a String
object to add() , which creates a JMenuItem object and adds it to the pop-up. A reference to the menu item
object is always returned by the various overloaded add() methods. Handling the events for the menu items
is a process identical to that for regular menu items, and Action objects handle their own events, as you
have seen.
You now add menu items to the pop-up that you have created as a member of a SketcherFrame object
by adding the following method to the SketcherFrame class:
// Create pop-up menu
private void createPopupMenu() {
Search WWH ::




Custom Search