Java Reference
In-Depth Information
Initial position
start
Move Operation
Ends Here
last
point
start
point
mouseDragged()
For each mouse
dragged event
deltaY
deltaX
is
last.x -
start.x
deltaY
is
last.y -
start.y
mouseDragged()
start
point
last
point
mouseDragged()
deltaY
and
start
is set to
last
for
the next event.
last
point
deltaX
deltaX
Each move will be from the previous cursor position stored in
start
, to the current cursor position
when the
MOUSE
_
DRAGGED
event occurred. The current cursor position will be obtained by calling the
getPoint()
method for the event object passed to the
mouseDragged()
method. Once each mouse
move has been processed, the current cursor position will then be stored in the variable
start
, ready
for the next event. For each
MOUSE
_
DRAGGED
event, we will move the element the distance between
successive cursor positions.
Try It Out - Moving Elements
Since the element classes are equipped to move, and we have kitted out
SketchView
to handle the menu
item action, we just need to add the code to the methods in
MouseHandler
. The
mousePressed()
method records the start point for a move, and it also sets up the
XOR
mode for drawing. That's precisely
what we will need to move or rotate elements, so we do not need to alter it at all.
We have to test for the setting of
mode
in the
mouseDragged()
method though, and, in principle,
execute different code depending on what it is. We have three possibilities:
NORMAL
, where we do as we
did before;
MOVE
, where we will execute a move operation; and
ROTATE
, which we will come to later.
Here's the new version of
mouseDragged()
to accommodate moving elements:
public void mouseDragged(MouseEvent e) {
last = e.getPoint(); // Save cursor position
if(button1Down && (theApp.getWindow().getElementType() != TEXT)
&& (mode == NORMAL)) {
if(tempElement == null) { // Is there an element?