How to draw star in java swing using fillPolygon
Solution 1
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.
Edit:
Solution 2
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
Solution 3
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);
Related videos on Youtube
Jay Gorio
Updated on July 13, 2022Comments
-
Jay Gorio almost 2 years
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); }
-
Jay Gorio over 8 yearsThanks for the quick response.
-
Jay Gorio over 8 yearsbut still cannot get the perfect 5 star.
-
Jay Gorio over 8 yearsThank you also for the references so much helpful