Java Reference
In-Depth Information
■
7.2
The model part
In this section we describe two classes that form the model part of our application:
Circle
and
CircleAdministration
. The first is an
abstract
representation of a
circle and the second is used to administer the circles currently in the drawing.
Here 'abstract' means that a
Circle
is independent of its graphical representation.
A circle is specified by defining two quantities: the location of the centre and its
radius. As we do not want to restrict ourselves to pixel coordinates, we use
double
variables. The class has methods to compute the distance of the centre to a given
point. The class
CircleAdministration
stores the circles that are currently in
the graphic. It also supplies methods to add a circle or to remove one.
7.2.1
Circles
Class
Circle
has three double fields,
x
,
y
and
radius
, which contain the co-
ordinates of the centre of the circle and its radius, respectively. Following the
object-oriented paradigm of Java, only the class
Circle
knows how to draw a cir-
cle. Therefore,
Circle
provides a method
draw
which contains the graphics com-
mands to draw the circle. These commands need a graphics reference (
Graphics
)
which is given as an argument to
draw
. Note that the
draw
-method of class
Circle
!
actually is a view part method. Thus, the distinction of view and model part in
this case is not only
between
classes but also
inside
a single class: some methods
handle 'view' aspects and others 'model' aspects.
The data on the centre and radius of the circle are stored as double; the draw
method, however, needs integers. We convert double to integers by simply round-
ing to the nearest integer. We shall learn about a better and more flexible way of
converting to pixel coordinates in Section 13.3. The
fillOval
-method expects
the upper right corner of the bounding box and the width and height of the box
as parameters. The coordinates are found by subtracting the radius from the co-
ordinates of the centre of the circle. By multiplying the radius by two we find the
width and height. To keep the code short we do not check whether the values are
plausible, e.g. that the radius or the pixel coordinates are non-negative.
Class
Circle
also supplies the method
distance(double x1, double y1)
which computes the Euclidean distance between the circle's centre and the point
(
x
1
,
y
1
). This method is used to determine which circle is closest to the location
of a mouse click and has to be deleted.
File:
its/InteractiveGraphic/Circle.java
package
its.InteractiveGraphic;
1.
2.
3.
import
java.awt.Graphics;
4.
5.
public class
Circle
{
6.
7.
Search WWH ::
Custom Search