Jay Gorio
Jay Gorio

Reputation: 335

How to draw star in java swing using fillPolygon

I'm having trouble setting the coordinate of the star are there any better solution for this. I cannot get the the correct shape. Can someone help me on this?

  public void star(Graphics shapes)
{
    shapes.setColor(color);
    int[] x  = {42,52,72,52,60,40,15,28,9,32,42};
    int [] y = {38,62,68,80,105,85,102,75,58,20,38};
    shapes.fillPolygon(x, y, 5);
}

Upvotes: 2

Views: 13953

Answers (5)

user14911327
user14911327

Reputation: 1

a star has 10 points ppl mind that not 11

setBackground(Color.black);  
    int[]x={250,150,0,150,100,250,400,350,500,350};
    int[]y={100,200,200,300,400,300,400,300,200,200};
    g.fillPolygon( (x),(y),10);         
    setForeground(Color.cyan);

this will help to draw a star with black bg and cyan foreground

Upvotes: 0

EmeralDragoness
EmeralDragoness

Reputation: 11

The second to last number of your Y should be 60 not 20

g2.setColor(color);
int[] x  = {42,52,72,52,60,40,15,28,9,32,42};
int[] y = {38,62,68,80,105,85,102,75,58,60,38};
g2.fillPolygon(x , y, 11);

Upvotes: 1

camickr
camickr

Reputation: 324108

I'm having trouble setting the coordinate of the star are there any better solution for this

Check out Playing With Shapes. You should be able to use the ShapeUtils class to generate your shape.

This class will generate the points for you so you don't need to manage every pixel.

Upvotes: 0

MadProgrammer
MadProgrammer

Reputation: 347194

Honestly, I'd use the 2D Graphics shapes API, they allow you to "draw" a shape, which is simpler (IMHO) then using polygon. The advantage is, they are easy to paint and transform

Having said that, the problem you're actually having is the fact that you're not passing the right information to the fillPolygon method.

If you take a look at the JavaDocs for Graphics#fillPolygon, you'll note that the last parameter is the number of points:

nPoints - a the total number of points.

But you're passing 5, where there are actually 11 points in your array

Something like...

shapes.setColor(color);
int[] x  = {42,52,72,52,60,40,15,28,9,32,42};
int [] y = {38,62,68,80,105,85,102,75,58,20,38};
shapes.fillPolygon(x, y, 11);

should now draw all the points, but some of your coordinates are slightly off, so you might want to check that

Upvotes: 2

SatyaTNV
SatyaTNV

Reputation: 4135

Sun's implementation provides some custom Java 2D shapes like Rectangle, Oval, Polygon etc. but it's not enough. There are GUIs which require more custom shapes like Regular Polygon, Star and Regular polygon with rounded corners. The project provides some more shapes often used. All the classes implements Shape interface which allows user to use all the usual methods of Graphics2D like fill(), draw(), and create own shapes by combining them.

Regular Polygon Star

Edit:

Link

Upvotes: 2

Related Questions