I have an applet that has an inner class that extends JComponent. This inner class has a paint method that draws a number of Stars. The Star class is defined as a separate class that implements Shape in the same package. A Star is made from a GeneralPath. This all works fine. My problem is that I don't know how to fill the Stars that I have drawn. I get a NullPointerException.
Here's the code (empty methods and imports omitted to keep it brief).
<code>
public class StarApplet
extends JApplet {
DrawingPane pane = new DrawingPane();
public void init() {
setContentPane(pane);
setSize(600, 400);
}
class DrawingPane
extends JComponent {
public void paint(Graphics g) {
Graphics2D g2D = (Graphics2D) g;
Star star = new Star(0, 0, 10, 15);
float delta = 40f; // increment between stars
float starty = 0f; // staring y position
float startx = 0f;
for (int i = 0; i < 8; i++) {
starty += delta;
startx = 0f;
for (int k = 0; k < 8; k++) {
startx += delta;
g2D.setColor(Color.BLUE);
g2D.draw(star.atLocation(startx, starty));
g2D.fill( (Shape) star);
}
}
}
}
}</code>
And this is my Star class
<code>
class Star {
/**start point of general path that forms the star*/
private Float start;
/**path that defines the star*/
private GeneralPath path;
private float sideLength;
private float centreSquareSize;
/**constructor*/
public Star(float x,float y,float centreSquareSize,float sideLength){ // has to be float as this is what moveTo needs so it saves us some casting overhead
start = new Point2D.Float(x,y);
this.sideLength = sideLength;
this.centreSquareSize = centreSquareSize;
createStar();
}
/**Called by the constructor to do all the work in defining the star*/
private void createStar() {
Point2D.Float point = start;
path = new GeneralPath();
path.moveTo(point.x,point.y); //Adds a point to the path by moving to the specified coordinates.
point = goTo(path,point,sideLength,-centreSquareSize);
point = goTo(path,point,centreSquareSize,-sideLength);
point = goTo(path,point,centreSquareSize,sideLength);
point = goTo(path,point,sideLength,centreSquareSize);
point = goTo(path,point,-sideLength,centreSquareSize);
point = goTo(path,point,-centreSquareSize,sideLength);
point = goTo(path,point,-centreSquareSize,-sideLength);
path.closePath();
}
private Point2D.Float goTo(GeneralPath path, Float point, float xFactor, float yFactor) {
path.lineTo(point.x+xFactor,point.y+yFactor); //Adds a point to the path by drawing a straight line from the current coordinates to the new specified coordinates.
point = (Point2D.Float)path.getCurrentPoint();
return point;
}
public Shape atLocation(float x, float y) {
start.setLocation(x, y);
path.reset();
createStar();
return path;
}
public Shape getShape(){
return path;
}
}
</code>