Java Reference
In-Depth Information
The first step is already in place - the actionPerformed() method in SketchView already sets ROTATE
mode in response to the Rotate menu action. The user will then drag the element to the angle required with
the mouse, while holding button 1 down. We need to work out the rotation angle for each MOUSE _ DRAGGED
event. The diagram below shows what happens when the mouse is dragged for a rotation.
mousePressed()
start
position
angle
angle
last
sin(angle) = perp/hypotenuse
mouseDragged()
Therefore:
angle = sin -1 (perp/hypotenuse)
The angle in the diagram is exaggerated so we can see what is going on. The mousePressed()
method is called when the button is first pressed at some arbitrary position and the cursor position is
recorded in start . When the mouseDragged() method is called, we record the cursor position in
last , and we now need to calculate angle . We must apply a little high school math to get this, which
you can ignore if you are rusty with trigonometry.
We can get the length of the perpendicular from the point start to the line extending from position
to last with a static method in the Line2D class:
double perp = Line2D.ptLineDist(position.x, position.y,
last.x, last.y,
start.x, start.y);
The ptLineDist() method calculates the perpendicular distance of the point specified by the last two
arguments, to the line specified by the first four arguments - the first pair of arguments being the
coordinates of the beginning of the line, and the second pair being the coordinates of the end point.
We know how to get the distance from position to start . We just apply the distance() method
that is defined in the Point class:
double hypotenuse = position.distance(start);
From the diagram you can see that we can calculate angle as:
sin-1(perp/hypotenuse)
Search WWH ::




Custom Search