Java Reference
In-Depth Information
of the bounding rectangle if you temporarily comment out the statements that do this. You see that rect-
angles are drawn with the right and bottom edges missing.
Defining Circles
The most natural mechanism for drawing a circle is to make the point where the mouse button is pressed the
center, and the point where the mouse button is released the end of the radius — that is, on the circumferen-
ce. You need to do a little calculation to make it work this way.
Figure 19-26 illustrates the drawing mechanism for a circle. Circles are drawn dynamically as the mouse
is dragged, with the cursor position being on the circumference of the circle. You have the center of the circle
and a point on the circumference available in the methods that handle the mouse events, but the Ellipse2D
class that you use to define a circle expects it to be defined by the coordinates of the point on the top-right
corner of the rectangle that encloses the circle plus its height and width. This means you have to calculate
the position, height, and width of the rectangle from the center and radius of the circle.
FIGURE 19-26
Pythagoras' theorem provides the formula that you might use to calculate the radius of the circle from the
point at the center and any point on the circumference, and this is shown in Figure 19-26 . The formula may
look a little complicated, but Java makes this easy. Remember the distance() method defined in Point2D
class? That does exactly what is shown here, so you are able to use that to obtain the radius directly from the
two defining points. When you have the radius, you can then calculate the coordinates of the top-left point
by subtracting the radius value from the coordinates of the center. The height and width of the enclosing
rectangle for the circle are just twice the radius.
TRY IT OUT: Adding Circles
Here's how this is applied in the definition of the Element.Circle class:
 
 
Search WWH ::




Custom Search