Java Reference
In-Depth Information
We get hold of a reference to the pop-up menu object by calling
getPopup()
for the object reference
returned by the application object's
getWindow()
method. The component where the pop-up is to
appear is identified in the first argument to the
show()
method for the pop-up by calling
getSource()
for the
MouseEvent
object,
e
. This will return a reference to the view, as type
Object
,
so we need to cast this to the
Component
type since that is what the
show()
method for the pop-up
expects. The position, which we store temporarily in
start
, is just the current cursor position when the
mouse button is released. We could use the position stored in
start
by the
mousePressed()
method, but if the user drags the cursor before releasing the button, the menu will appear at a different
position from where the button is released.
If you recompile Sketcher and run it again, you should get the pop-up menu appearing in response to a
right button click, or whatever button triggers a context menu on your system.
Note how we get the
Icons
and the label for each of the menu items. This is because we have defined
both in the
Action
objects that we used to generate the menu.
How It Works
The
isPopupTrigger()
method for the
MouseEvent
object returns
true
when the button
corresponding to a context menu is pressed or released. In this case we call the
show()
method for the
pop-up menu object that we created in the
SketchFrame
object. When you click on a menu item in
the pop-up, or click elsewhere, the pop-up menu is automatically hidden. Now any element type or
color is a couple of clicks away.
This is just a pop-up menu, not a context menu. A context menu should be different depending on
what's under the cursor. We will now look more closely at how we could implement a proper context
menu capability in Sketcher.