Java Reference
In-Depth Information
AffineTransform old = g2D.getTransform(); // Save the current transform
// Add translation transform to current
g2D.translate((double)position.x, (double)position.y);
g2D.rotate(angle); // Rotate about position
// Reference point for drawString() is the baseline of the 1st character
g2D.drawString(text, origin.x + 2, maxAscent + 2);
g2D.setTransform(old); // Restore original transform
g2D.setFont(oldFont); // Restore the old font
}
Directory "Sketcher 10 moving and rotating elements"
A single line of code does it here, too. Implementing the GUI process for rotating elements is a bit harder.
Rotating Elements
You have implemented the mechanism for the elements to be drawn rotated, so all you need to figure out is
the mechanics of how the user accomplishes the rotation of an element, and how this is communicated to
the Element object.
The first step is already in place — the actionPerformed() method in the anonymous class for the
Rotate listener already sets ROTATE mode, and saves the reference to the highlighted element in selec-
tedElement in response to the Rotate menu action. The user then drags the element to the angle re-
quired with the mouse while holding button 1 down. You need to work out the rotation angle for each
MOUSE_DRAGGED event. Figure 20-21 shows what happens when the mouse is dragged for a rotation.
FIGURE 20-21
The concept behind rotating an element is very simple. Imagine a rigid rod between position and the
mouse cursor. The rod is fixed to position but free to rotate about that point, and the cursor can slide up
and down the rod as it is dragged. The element to be rotated is bonded to the rod and therefore rotates with it
 
 
Search WWH ::




Custom Search