Java Reference
In-Depth Information
To deal with ROTATE mode in the mouseDragged() method, you can add code to the ROTATE case in the
switch statement:
case ROTATE:
// Rotating an element
if(buttonState == MouseEvent.BUTTON1 && selectedElement !=
null) {
angle += getAngle(selectedElement.getPosition(), start,
last);
if(angle != 0.0) { // If there is
rotation...
// ...rotate the element
selectedElement.setRotation(oldAngle + angle);
repaint(); // Repaint the view
start = last; // last is start
next time
}
}
break;
Directory "Sketcher 10 moving and rotating elements"
This uses a helper method, getAngle() . You can add it to the MouseHandler class as:
// Helper method for calculating the rotation angle
double getAngle(Point position, Point start, Point last) {
// Get perpendicular distance from last to line from position
to start
double perp = Line2D.ptLineDist(position.x, position.y,
last.x, last.y, start.x,
start.y);
// Get the distance from position to start
double hypotenuse = position.distance(start);
if(perp < 1.0 || hypotenuse < 1.0) return 0.0; // Ensure
sensible values
// Angle is the arc sine of perp/hypotenuse. Clockwise is
positive angle
return -Line2D.relativeCCW(position.x, position.y, start.x,
start.y,
last.x, last.y)*Math.asin(perp/
hypotenuse);
Search WWH ::




Custom Search