Java Reference
In-Depth Information
How It Works
This last piece is relatively trivial. The additional menu is added to the menubar 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 window one third of the way in from the top and left sides of the application
window. It then calls
setVisible()
for the dialog object to display it.
Pop-up Menus
The
javax.swing
package defines a class,
JPopupMenu
, that 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. 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 is primarily for identification purposes and is not always displayed when the menu is popped up: it
depends on your environment. Under Windows for instance 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.
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 or
Action
objects by
passing each of them to the
add()
method for the
JPopupMenu
object. You can also pass a
String
object to
add()
, which will create a
JMenuItem
object and add 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 an identical process to that for regular menu items, and
Action
objects handle
their own events as we have seen.
We will now add menu items to the pop-up we created above by adding the following code to the
class constructor:
// Create pop-up menu
popup.add(lineAction);
popup.add(rectangleAction);
popup.add(circleAction);
popup.add(curveAction);
popup.add(textAction);
popup.addSeparator();
popup.add(redAction);
popup.add(yellowAction);
popup.add(greenAction);
popup.add(blueAction);