Java Reference
In-Depth Information
We
first
create
an
AffineTransform
object that
applies
a
translation
to
the
point,
position
.
Then
we
apply
the
createTransformedShape()
method to the rectangle that is passed as the argument -
which will be the bounding rectangle for a shape at (0, 0) - to get a corresponding shape translated to its
proper position. Even though we get a
GeneralPath
object back, we can get a rectangle from that
quite easily by calling its
getBounds()
method. Thus our helper method accepts a reference to an
object of type
java.awt.Rectangle
, and returns a reference to the rectangle that results from
translating this to the point,
position
. This is precisely what we want to do with the bounding
rectangles we get with our shapes defined at the origin. We can now use this to implement the
getBounds()
method for the
Element.Line
class:
public java.awt.Rectangle getBounds() {
return getBounds(line.getBounds());
}
We just pass the reference to the
line
member of the class as the argument to the base class version of
getBounds()
, and return the rectangle that is returned by that method. The
getBounds()
methods
for the nested classes
Rectangle
,
Circle
, and
Curve
will be essentially the same - just change the
argument to the base class
getBounds()
call to the
Shape
reference corresponding to each class. To
implement the
getBounds()
method for the
Text
class, just pass the
bounds
member of that class as
the argument to the base class
getBounds()
method.
We must also update the
modify()
method, and this is going to be specific to each class. To adjust the
end point of a line so that it is relative to the start point at the origin, we must change the method in the
Element.Line
class as follows:
public void modify(Point start, Point last) {
line.x2 = last.x - position.x;
line.y2 = last.y - position.y;
}
That's the
Element.Line
class complete. We can apply the same thing to all the other classes in the
Element
class.
Translating Rectangles
Here's the changes to
Element.Rectangle
constructor:
public Rectangle(Point start, Point end, Color color) {
super(color);
position = new Point(Math.min(start.x, end.x),
Math.min(start.y, end.y));
rectangle = new Rectangle2D.Double(origin.x,
origin.y,
Math.abs(start.x - end.x), // Width
Math.abs(start.y - end.y)); // & height
}