Java Reference
In-Depth Information
public void draw(Graphics2D g2D) {
g2D.setPaint(highlighted ? Color.MAGENTA : color); // Set the line color
AffineTransform old = g2D.getTransform(); // Save the current transform
AffineTransforn new = AffineTransform.getTranslateInstance(
position.x, position.y); // Translate to position
g2D.setTransform(new); // Set the new transform
g2D.draw(line); // Draw the line
g2D.setTransform(old);
// Restore original transform
}
Directory "Sketcher 9 using affine transforms to draw elements"
Saving a copy of the old transform is most important, because that enables you to restore the original
scheme after you've drawn the line. If you don't do this, subsequent draw operations in the same graphics
context have more and more translations applied cumulatively, so objects get further and further away from
where they should be. This occurs in the
mouseDragged()
handler that deals with creating geometric shapes.
Only one line of code involves the element itself and that is the following statement:
g2D.draw(line); // Draw the line
All the rest are common to all the geometric shapes —
Element.Text
is the sole exception. You could
economize on the amount of code by adding an overloaded
draw()
method to the
Element
base class that
you can define like this:
protected void draw(Graphics2D g2D, Shape element) {
g2D.setPaint(highlighted ? HIGHLIGHT_COLOR : color); // Set the element color
AffineTransform old = g2D.getTransform();
// Save the current transform
// Add a translation to current transform
g2D.translate((double)position.x, (double)position.y);
g2D.draw(element);
// Draw the element
g2D.setTransform(old);
// Restore original transform
}
Directory "Sketcher 9 using affine transforms to draw elements"
This method is inherited in all the derived classes. The
translate()
method that accepts
double
argu-
ments adds a translation to the existing transform in the graphics context. Thus this
draw()
method draws
any
Shape
object after applying a translation to the point
position
. You can now call this method from the
draw()
method in the
Element.Line
class: