Java Reference
In-Depth Information
Otherwise,themousecoordinatesaresavedin
dragX
and
dragY
variablestorecord
theoriginofthedragoperation,andthe
dragging
Booleanvariableisassigned
true
sothattheshapeisdraggedonlywhenthemousecursorisovertheshapewhenthedrag
operation begins.
During a drag operation, the mouse motion listener's
void
mouseDragged(MouseEvent me)
method is invoked. Its first task is to test
dragging
toseeifthemousecursorwasovertheshape.Ifthisvariablecontainsfalse,
thismethodreturns.(Withoutthistest,pressingthemousebuttonwhilethemousecurs-
or was not on the round rectangle, and then starting to drag the mouse cursor, would
resultintheshapesnappingtothelocationofthedragandsubsequentlybeingdragged.)
If
dragging
contains true,
mouseDragged()
next calculates a new upper-left
corneroriginfortheroundrectanglebyoffsettingitscurrentoriginwiththedifference
between the current mouse coordinates and the coordinates saved in
dragX
and
dragY
. It then passes the new origin along with the current size and arc radius to the
round rectangle via a
setRoundRect()
method call.
Continuing, a call to
repaint()
causes the round rectangle to be repainted at the
newlocation,andapairofassignmentstatementsupdate
dragX
and
dragY
tothecur-
rentmousecoordinatessothatthenextcallto
mouseDragged()
calculatesthenew
round rectangle origin relative to the origin that was just calculated.
When the mouse button is released, the mouse listener's
void
mouseReleased(MouseEvent me)
method is called. This method assigns
false
to
dragging
so that the shape isn't dragged when a drag operation is subse-
quently started but the mouse cursor isn't over the shape when that operation begins.
Compile this source code (
javac DragRect.java
) and run the application
gress.