Java Reference
In-Depth Information
This is large enough to accommodate our stars. If you
compile and run the applet, you should see the
AppletViewer window shown here.
How It Works
The Star class has a GeneralPath object, p , as a member. The constructor sets the coordinates of the
start point from the arguments, and calls the createStar() method that creates the path for the
star. The first line is drawn relative to the start point that is set by the call to moveTo() for p . For
each subsequent line, we 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() .
We always need a Shape reference to draw a Star object, so we have included a getShape()
method in the class that simply returns a reference to the current GeneralPath object as type Shape .
The atLocation() method recreates the path at the new position specified by the arguments and
returns a reference to it.
The StarApplet class draws stars on a component defined by the inner class StarPane . We 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 coordinate 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
Once 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 results the boundary should be closed.
Let's try it out by modifying the applet example that displayed stars.
Try It Out - Filling Stars
To fill the stars we just need to call the fill() method for each star in the paint() m ethod of the
StarPane object. Modify the paint() method as follows:
public void paint(Graphics g) {
Graphics2D g2D = (Graphics2D)g;
Star star = new Star(0,0); // Create a star
Search WWH ::




Custom Search