Java Reference
In-Depth Information
if((e.getButton() == e.BUTTON3)
// Code to display the pop-up menu...
Now the pop-up would only operate with button 3, regardless of the convention for the underlying
operating system, but the user may not be particularly happy about having to use a different popup
trigger for your Java program compared to other applications on the same system.
We will try a pop-up menu in Sketcher assuming Windows is the applicable environment. You should
be able to change it to suit your environment if it is different, or even add the same code for both
MOUSE
_
PRESSED
and
MOUSE
_
RELEASED
events if you wish.
Try It Out - Displaying a Pop-up Menu
In Sketcher, the pop-up menu would sensibly operate in the area where the sketch is displayed - in
other words triggering the pop-up menu has to happen in the view. Assuming you have already added
the code that we discussed in the previous section to
SketchFrame
, we just need to add a method to
SketchFrame
to make the pop-up available to the view:
// Retrieve the pop-up menu
public JPopupMenu getPopup() {
return popup;
}
Now a
SketchView
object can get a reference to the pop-up in the
SketchFrame
object by using the
application object to get to this method.
We will implement the pop-up triggering in the
mouseReleased()
method consistent with Windows,
but remember, all you need to do to make your code general is to put it in the
mousePressed()
method too. Here's how
mouseReleased()
should be in the
MouseHandler
inner class to
SketchView
:
public void mouseReleased(MouseEvent e) {
if(e.isPopupTrigger()) {
start = e.getPoint();
theApp.getWindow().getPopup().show((Component)e.getSource(),
start.x, start.y);
start = null;
} else if((e.getButton()==MouseEvent.BUTTON1) &&
(theApp.getWindow().getElementType() != TEXT)) {
button1Down = false; // Reset the button 1 flag
if(tempElement != null) {
theApp.getModel().add(tempElement); // Add element to the model
tempElement = null; // No temporary now stored
}
if(g2D != null) { // If there's a graphics context
g2D.dispose(); // ...release the resource
g2D = null; // Set field to null
}
start = last = null; // Remove the points
}
}