Java Reference
In-Depth Information
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 circumference. We'll need to do a little calculation for this.
The diagram illustrates the drawing mechanism. Circles will be drawn dynamically as the mouse is dragged,
with the cursor position being on the circumference of the circle. Pythagoras' theorem, as shown in the
diagram, provides the formula that you might use to calculate the radius from the point at the center and the
point on the circumference. However, Java makes this easy. Remember the distance() method defined in
Point2D class? That does exactly what is shown here so we will be able to use that to obtain the radius
directly. When we have that we can then calculate the top-left point by subtracting the radius from the
coordinates of the center. We will create a circle shape as a particular case of an Ellipse2D object and so
the height and width of the enclosing rectangle will be just twice the radius.
Try It Out - Adding Circles
Here's how this is applied in the definition of the Element.Circle class:
class Element {
// Code defining the base class...
// Nested class defining a line...
// Nested class defining a rectangle...
// Nested class defining a circle
public static class Circle extends Element {
public Circle(Point center, Point circum, Color color) {
super(color);
// Radius is distance from center to circumference
double radius = center.distance(circum);
circle = new Ellipse2D.Double(center.x - radius, center.y - radius,
2.*radius, 2.*radius );
}
Search WWH ::




Custom Search