Java Reference
In-Depth Information
NOTE The translate() method you are using here to move the origin of the device context
has two parameters of type int . The Graphics2D class defines another version of this method
thathastwoparametersoftype double andhasaslightlydifferentroleindrawingoperations.
I'll introduce you to the second version of translate() in Chapter 20.
Defining Rectangles
The interactive mechanism for drawing a rectangle is similar to that for a line. When you are drawing a rect-
angle, the point where the mouse is pressed defines one corner of the rectangle, and as you drag the mouse,
the cursor position defines an opposite corner, as illustrated in Figure 19-24 .
FIGURE 19-24
Releasing the mouse button establishes 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 al-
ways defined by the top-left corner, plus a width and a height.
Figure 19-24 shows the four possible orientations of the mouse path as it is dragged in relation to the
rectangle drawn. The top-left corner has coordinates that are the minimum x and the minimum y from the
points at the ends of the diagonal. The width is the absolute value of the difference between the x coordinates
for the two ends, and the height is the absolute value of the difference between the y coordinates. From that
you can define the Rectangle class for Sketcher.
TRY IT OUT: The Element.Rectangle Class
Here's the definition of the class for a rectangle object:
 
 
Search WWH ::




Custom Search