Java Reference
In-Depth Information
public void draw(Graphics2D g2D) {
draw(g2D, line);
// Call base draw method
}
Directory "Sketcher 9 using affine transforms to draw elements"
You can now go ahead and implement the
draw()
method in exactly the same way for all the nested
classes to
Element
, with the exception of the
Element.Text
class. Just pass the underlying
Shape
reference
for each class as the second argument to the overloaded
draw(
) method. You can't use the base class helper
method in the
Element.Text
class because text is not a
Shape
object. You have to treat the class defining
text as a special case.
Translating Text
The only changes that you need to make to use a transform to draw a
Text
element are to the
draw()
method
in the
Element.Text
class:
public void draw(Graphics2D g2D) {
g2D.setPaint(highlighted ? HIGHLLIGHT_COLOR : color);
Font oldFont = g2D.getFont(); // Save the old font
g2D.setFont(font); // Set the new font
AffineTransform old = g2D.getTransform();
// Save the current transform
// Add translation transform to current
g2D.translate((double)position.x, (double)position.y);
g2D.drawString(text, origin.x, origin.y+(int)bounds.getHeight());
g2D.setTransform(old);
// Restore original transform
g2D.setFont(oldFont); // Restore the old font
}
Directory "Sketcher 9 using affine transforms to draw elements"
This doesn't seem to have moved things any further forward compared to the code that was there before,
so why is this useful? Well, you want to be able to move and rotate all the elements, including
Text
ele-
ments, and introducing an affine transform into the drawing process makes this possible.