Java Reference
In-Depth Information
How It Works
The
Star
class has a
GeneralPath
object,
p
, as a static member that references the path for a star. There's
no need to create
Star
objects as all we are interested in is the path to draw a star.
The static
starAt()
method creates the path for a star at the position
point
that is defined by the argu-
ments. The first line is drawn relative to the start point that is set by the call to
moveTo()
for
p
. For each
subsequent line, you retrieve the current position by calling
getCurrentPoint()
for
p
and drawing the
line relative to that. The last line to complete the star is drawn by calling
closePath()
. A reference to
the
GeneralPath
object,
p
, that results is returned.
The
StarApplet
class draws stars on a component defined by the inner class
StarPane
. You draw the
stars using the
paint()
method for the
StarPane
object, which is a member of the
StarApplet
class.
Each star is drawn in the nested loop with the position specified by (
x,y
). The
y
coordinate defines the
vertical position of a row, so this is incremented by delta on each iteration of the outer loop. The coordin-
ate
x
is the position of a star within a row so this is incremented by delta on each iteration of the inner
loop.
FILLING SHAPES
After you know how to create and draw a shape, filling it is easy. You just call the
fill()
method for the
Graphics2D
object and pass a reference of type
Shape
to it. This works for any shape, but for sensible res-
ults the boundary should be closed. The way the enclosed region is filled is determined by the window rule
in effect for the shape.
Let's try it out by modifying the applet example that displayed stars.
TRY IT OUT: Filling Stars
To fill the stars you just need to call the
fill()
method for each star in the
paint()
method of the
StarPane
object. Modify the
paint()
method as follows: