[java] drawPolygon

Started by
8 comments, last by mdog 17 years ago
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.
Advertisement
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.
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.
how do you calculate the second point of an equilateral tri?
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]
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..
The last argument to the function is wrong - it should be 3. Your yValue is also wrong by the way.
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?
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.

This topic is closed to new replies.

Advertisement