Marco Atef Marco Atef - 7 months ago 20
Java Question

Drawing a Star using JApplets

I'm working on a project which I have to draw a Star in the middle of an Applet, here's the code I've been working on:

int[] xPoints = { 55, 67, 109, 73, 83, 55, 27, 37, 1, 43 };
int[] yPoints = { 0, 36, 36, 54, 96, 72, 96, 54, 36, 36 };

Graphics2D g2d = ( Graphics2D ) g;
GeneralPath star = new GeneralPath();
star.moveTo( xPoints[ 0 ], yPoints[ 0 ] );

for ( int count = 1; count < xPoints.length; count++ )
star.lineTo( xPoints[ count ], yPoints[ count ] );
star.closePath();

g2d.setColor(color);
g2d.fill(star);


It draws a Star in the left side of the Applets, and I can't modify those x,y points to make it to the center. Also those points are not stable, they don't draw a stable star. I'll be glad if someone can help.

Answer

To change the location of the star, an offset for each point must be created.

int centerX = 0;
int centerY = 0;

By using these, you need to update the position of the points by adding the offset:

star.moveTo(xPoints[0] + centerX, yPoints[0] + centerY);

and

star.lineTo(xPoints[count] + centerX, yPoints[count] + centerY);

With the final code being:

int centerX = 0;
int centerY = 0;

int[] xPoints = { 55, 67, 109, 73, 83, 55, 27, 37, 1, 43 };
int[] yPoints = { 0, 36, 36, 54, 96, 72, 96, 54, 36, 36 };

Graphics2D g2d = (Graphics2D) g;
GeneralPath star = new GeneralPath();
star.moveTo(xPoints[0] + centerX, yPoints[0] + centerY);

for (int count = 1; count < xPoints.length; count++)
    star.lineTo(xPoints[count] + centerX, yPoints[count] + centerY);
star.closePath();

g2d.setColor(color);
g2d.fill(star);