Java Reference
In-Depth Information
}
public abstract java.awt.Rectangle getBounds();
public abstract void modify(Point start, Point last);
public abstract void draw(Graphics2D g2D);
protected Color color; // Color of a shape
protected boolean highlighted = false; // Highlight flag
final static Point origin = new Point(); // Point 0,0
protected Point position; // Element position
// Definitions for our shape classes...
}
You might consider passing the start point to the Element constructor, but this wouldn't always work.
This is because we need to figure out what the reference point is in some cases - for rectangles, for
example. The position of a rectangle will be the top left corner, which is not necessarily the start point.
We have included a method to retrieve the position of an element, as we are sure to need it. We also
have added another member, origin , which is the point (0, 0). This will be useful in all the derived
classes, as we will now draw every element at that point. Since we only need one, it is static , and
since we won't want to change it, it is final .
Let's start with the nested class, Line .
Translating Lines
We need to update the constructor first of all:
public Line(Point start, Point end, Color color) {
super(color);
position = start;
line = new Line2D.Double(origin, new Point(end.x - position.x,
end.y - position.y));
}
We've saved the point start in position , and created the Line2D.Double shape as the origin. Of
course, we have to adjust the coordinates of the end point so that it is relative to (0, 0).
We can now implement the draw() method to use a transform to move the coordinate system to where
the line should be drawn. We can economize on the code in the element classes a little by thinking
about this because a lot of the code is essentially the same. Here's how we would implement the method
for the Element.Line class directly:
public void draw(Graphics2D g2D) {
g2D.setPaint(highlighted ? Color.MAGENTA : color); // Set the line color
AffineTransform old = g2D.getTransform(); // Save the current transform
g2D.translate(position.x, position.y); // Translate to position
g2D.draw(line); // Draw the line
g2D.setTransform(old); // Restore original transform
}
Search WWH ::




Custom Search