Java Reference
In-Depth Information
Defining the Other Context Menu
The context menu when the cursor is over an element should be implemented in the view. We already
have the menu defined in SketchFrame for when the cursor is not over an element. All we need is the
context menu for when it is - plus the code to decide which menu to display when
isPopupTrigger() returns true for a mouse event.
You already know that we will have four menu items in the element context menu:
Move - to move the element under the cursor to a new position. This will work by dragging it
with the left mouse button down (button 1).
Delete - this will delete the element under the cursor.
Rotate - this will allow you to rotate the element under the cursor about the top-left corner of
its bounding rectangle by dragging it with the left mouse button down.
Send-to-back - this is to overcome the problem of an element not being accessible, never
highlighted that is, because it is masked by the bounding rectangle of another element.
Since we highlight an element by searching the list from the beginning, an element towards the end may
never be highlighted if the rectangle for an earlier element completely encloses it. Moving the earlier
element that is hogging the highlighting to the end of the list will allow the formerly masked element to
be highlighted.
Try It Out - Creating Context Menus
We will add the necessary data members to the SketchView class to store the element pop-up
reference, and the JMenuItem objects that will be the pop-up menu items:
private JPopupMenu elementPopup = new JPopupMenu("Element");
private JMenuItem moveItem, deleteItem,rotateItem, sendToBackItem;
We must add import statements for JPopupMenu and JMenuItem :
import javax.swing.JPopupMenu;
import javax.swing.JMenuItem;
We will create the elementPopup context menu in the SketchView constructor:
public SketchView(Sketcher theApp) {
this.theApp = theApp;
MouseHandler handler = new MouseHandler(); // create the mouse listener
addMouseListener(handler); // Listen for button events
addMouseMotionListener(handler); // Listen for motion events
// Add the pop-up menu items
moveItem = elementPopup.add("Move");
deleteItem = elementPopup.add("Delete");
rotateItem = elementPopup.add("Rotate");
sendToBackItem = elementPopup.add("Send-to-back");
Search WWH ::




Custom Search