19.5. 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. The way the enclosed region will be 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:

public void paint(Graphics g) {
      Graphics2D g2D = (Graphics2D)g;
      Star star = new Star(0,0);                 // Create a star
      float delta = 60;                          // Increment between stars
      float starty = 0;                          // Starting y position

      // Draw 3 rows of 4 stars
      for(int yCount = 0 ; yCount<3; yCount++) {
  
        starty += delta;                         // Increment row position
        float startx = 0;                        // Start x position in a row

        // Draw a row of 4 stars
        for(int xCount = 0 ; xCount<4; xCount++) {
          g2D.setPaint(Color.BLUE);              // Drawing color blue
          g2D.draw(star.atLocation(startx += delta, starty));
          g2D.setPaint(Color.GREEN);             // Color for fill is green
          g2D.fill(star.getShape());             // Fill the star
        }
      }
    }

You also need an import statement for the Color class name in the StarApplet.java source file:

import java.awt.Color;

Now the applet window will look something like that shown in Figure 19-19, but in color, of course.

Figure 19.19. Figure 19-19

19.5.1. ...

Get Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.