I'm writing a drawing program and one feature I would like to implement is arbitrarily sided shapes. I have most of the features worked out, but one thing I need is a function to generate a Polygon
object from an integer representing a number of sides. I don't remember much of trigonometry, although I'm sure that my problem involves some.

- 168,117
- 40
- 217
- 433

- 526
- 2
- 6
- 17
-
2Search for keywords "java" and ["regular polygon"](http://en.wikipedia.org/wiki/Regular_polygon), then report back with your [sscce](http://sscce.org/). – trashgod Jul 25 '11 at 20:44
-
2*"I don't remember much of trigonometry,"* Try to remember to ask a *question*. – Andrew Thompson Jul 25 '11 at 23:25
-
Even if you don't *remember* much trigonometry, if you're reasonably intelligent and motivated, you should have the ability to look it up and take a stab at things yourself. – Hovercraft Full Of Eels Jul 25 '11 at 23:28
2 Answers
There are two parts to your problem. First, you need an algorithm for generating points that comprise vertices of a polygon, which is a language-agnostic process. Based on the wording of your question, it seems like any polygon with the required number of sides works, so you could generate a regular polygon based on a circle of fixed radius.
For example, for the input 4
, your points might be (0, r)
, (r, 0)
, (0, -r)
and (-r, 0)
. You'd get those by drawing an imaginary/invisible circle of radius r
, then selecting points (sin(360/input)*r, cos(360/input)*r)
. (Keep in mind that Java's trig uses radians, not degrees, though.)
Once you have your points, you have to create the Polygon
object. There's a constructor that takes an array of x-coordinates and an array of y-coordinates, plus the total number of vertices, which is just your initial input. All you really have to do is pop the coordinates of your points into two arrays and you're all set.

- 30,199
- 37
- 136
- 151
-
+1 See also this [example](http://stackoverflow.com/questions/2508704/how-to-draw-a-circle-in-java-with-a-radius-and-points-around-the-edge/2510048#2510048). – trashgod Jul 26 '11 at 00:30
Hope this helps. It provides code for regular polygons. http://java-sl.com/shapes.html

- 56,971
- 9
- 68
- 98