Java Reference
In-Depth Information
public Shape getShape() {
return rectangle;
}
public java.awt.Rectangle getBounds() {
return rectangle.getBounds();
}
public void modify(Point start, Point last) {
rectangle.x = Math.min(start.x, last.x);
rectangle.y = Math.min(start.y, last.y);
rectangle.width = Math.abs(start.x - last.x);
rectangle.height = Math.abs(start.y - last.y);
}
private Rectangle2D.Double rectangle;
}
}
If you uncomment the line in the
createElement() method that creates rectangles
and recompile, you will be ready to draw rectangles
as well as lines.
You only need to recompile Element.java and
SketchView.java . The rest of Sketcher is still
the same. If you run it again, you should be able to
draw rectangles and lines - in various colors, too.
How It Works
The code works in essentially the same way as for lines. You can drag the mouse in any direction to
create a rectangle. The constructor sorts out the correct coordinates for the top-left corner. This is
because the rectangle is being defined from its diagonal, so the rectangle is always defined from the
point where the mouse button was pressed to the current cursor position. Because its top left corner
always defines the position of a Rectangle2D object, we can no longer tell from this object which
diagonal was used to define it.
Search WWH ::




Custom Search