Java Reference
In-Depth Information
Rectangle
class from the Java standard class library, but on further investigation
we realize that its role is not really consistent with our goals. In addition, no other
classes are defined for the other shapes we need.
So, as we envisioned in our architectural design, we consider having one
class per shape type:
Line
,
Oval
,
Rect
, and
Poly
. Remember that circles and
squares will just be specific instances of the
Oval
and
Rect
classes, respec-
tively. Each shape class will have a
draw
method that draws that kind of shape
on the screen.
Now let's consider the kind of information that each shape needs to store to be
able to draw itself. A line needs two points: a starting point and an ending point.
Each polyline, on the other hand, needs a list of points to define the start and end
points of each line segment. Both ovals and rectangles are defined by a bounded
rectangle, storing an upper-left corner and the width and height of the shape.
This analysis leads to the conclusion that
Oval
and
Rect
objects have some
common characteristics that we could exploit using inheritance. They could both,
for instance, be derived from a class called
BoundedShape
. Furthermore, because
all shapes have to be stored in the
ArrayList
object that we'll use to keep track
of the entire drawing, it would simplify the refinement to have a generic
Shape
class from which all drawn shapes are derived.
The
Shape
and
BoundedShape
classes are used for organizational purposes.
We do not intend to instantiate them; therefore they probably should be abstract
classes. In fact, if we define an
abstract
method called
draw
in the
Shape
class,
we could capitalize on polymorphism to simplify the drawing of the shapes in
the drawing area. A loop can move through the
ArrayList
, having each shape
(whatever it may be) draw itself.
After some consideration, we achieve the class diagram shown in Figure J.5.
This diagram specifically represents the classes that are important to the second
refinement of the
PaintBox
project.
Selecting a current color can be relegated to the
JColorChooser
component
provided by the Swing package. The color button will bring up the
JColorChooser
dialog box and respond accordingly to the user's selection.
Multiple shapes will accumulate on the drawing surface. We could define a
class to serve as a collection of the drawn shape objects. It could use an
ArrayList
to keep track of the list of shapes. Whenever the drawing area needs to be
refreshed, we can iterate through the list of shapes and draw each one in turn.
Figure J.6 shows the
PaintBox
program after the first two refinements have
been completed. Once again, we could visit with the client at this point to deter-
mine whether the evolution of the system meets with his or her satisfaction.
Search WWH ::
Custom Search