Java Reference
In-Depth Information
Defining Rectangles
The interactive mechanism for drawing a rectangle is similar to that for a line. When you are drawing a
rectangle, the point where the mouse is pressed will define one corner of the rectangle, and as you drag
the mouse the cursor position will define an opposite corner, as illustrated below.
Releasing the mouse button will establish the final rectangle shape to be stored in the model. As you
can see, the cursor position when you press the mouse button can be any corner of the rectangle. This is
fine from a usability standpoint, but our code needs to take account of the fact that a Rectangle2D
object is always defined by the top-left corner, plus a width and a height.
The diagram shows the four possible orientations of the mouse path as it is dragged in relation to the
rectangle drawn. The top-left corner will have coordinates that are the minimum x and the minimum y
from the points at the ends of the diagonal. The width will be the absolute value of the difference
between the x coordinates for the two ends, and the height will be the absolute value of the difference
between the y coordinates. From that we can define our class.
Try It Out - The Element.Rectangle Class
Here's the definition of the class for a rectangle object:
class Element {
// Code for the base class definition...
// Nested class defining a line...
// Nested class defining a rectangle
public static class Rectangle extends Element {
public Rectangle(Point start, Point end, Color color) {
super(color);
rectangle = new Rectangle2D.Double(
Math.min(start.x, end.x), Math.min(start.y, end.y), // Top-left corner
Math.abs(start.x - end.x), Math.abs(start.y - end.y)); // Width & height
}
Search WWH ::




Custom Search