Java Reference
In-Depth Information
Note how you get the icons, the label and the accelerator key combination, for each of the menu items.
This is because both are defined in the Action objects that were used to generate the menu. You could
remove the icons by calling the setIcon() method for the menu items with the argument null .
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 you call the processPopupTrigger() method that
you implemented to display the pop-up menu. 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 really a context menu. A context menu should display a different menu
depending on what's under the cursor. You now look more closely at how you could implement a proper
context menu capability in Sketcher.
Implementing a Context Menu
As a context menu displays a different menu depending on the context, it follows that the program needs
to know what is under the cursor at the time the pop-up trigger button is pressed. Let's take the specific
instance of the view in Sketcher where you are listening for mouse events. You could define two contexts
for the cursor in the view — one when an element in the view is under the cursor and another when there
is no element under the cursor. In the first context, you could display a special pop-up menu that provides
operations that apply specifically to the element under the cursor — to delete or move the element, for ex-
ample. In the second context, when there is no element under the cursor, you could display the pop-up menu
that you created in the previous example. The context menu that is displayed when an element is under the
cursor is going to look like that shown in Figure 20-13 .
FIGURE 20-13
 
 
Search WWH ::




Custom Search