# [java] drawPolygon

This topic is 4265 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hey, I was wondering how you would use the drawPolygon method to make an equilateral triangle. I've looked all over the place but am having no luck. Thanks.

##### Share on other sites
If you look up java API and look under the graphics object you'll find this:

drawPolygon(int[] xPoints, int[] yPoints, int nPoints)
Draws a closed polygon defined by arrays of x and y coordinates.

you need to calculate the x,y coordinates of each point of your equilateral triangle first, then put them into two integer arrays and then pass them to the drawPolygon method.

##### Share on other sites
CrewNick already beat me to it. Just calculate the third point. It's at (a/2, a*sin(60)) where a is the length of one side.

##### Share on other sites
how do you calculate the second point of an equilateral tri?

##### Share on other sites
In my previous post I assumed it's aligned with the x-axis, but that's not really a general case. This problem should still be easily solvable with trigonometry. Since I've opened my mouth, I'll draw you a diagram to explain it.

Edit: see my diagram. There may be some mistakes in the signs, I did not thoroughly check my thinking on that part; and I did not list all of them so that you can do some thinking on your own also (in case this is a homework question). Just draw some diagrams and think about where the points are relative to the pivot.

Edit2: found a mistake already, d should switch sign at β = 90

[Edited by - lightbringer on April 10, 2007 5:00:51 PM]

##### Share on other sites
heres what i came up with..

int yValue = (int)Math.sin(60);

g.fillPolygon( new int[] { point.x,(point.x+side/2),(point.x-side/2)}, new int[] {point.y,(point.y+yValue),(point.y+yValue)}, side );

but im getting an array index out of bounds error and i can't figure out why..

##### Share on other sites
The last argument to the function is wrong - it should be 3. Your yValue is also wrong by the way.

##### Share on other sites
i think my problem was i wasnt putting the degrees in radians so now my code looks like this...

int yValue = (int)Math.sin(60*(Math.PI/180));

g.fillPolygon( new int[] { point.x,(point.x+side/2),(point.x-side/2)}, new int[] {point.y,(point.y+yValue),(point.y+yValue)}, 3 );

now my error message goes away but nothing gets outputed.. any thoughts?

##### Share on other sites
Yes. Unless your triangle has side length equal to 1, your yValue is still wrong. Nevermind about the diagram, did you read my first post? :)

i solved it.

1. 1
2. 2
3. 3
Rutin
13
4. 4
5. 5

• 26
• 11
• 9
• 9
• 11
• ### Forum Statistics

• Total Topics
633699
• Total Posts
3013416
×