Create a Polygon with a loop in Java
Description
The following code shows how to create a Polygon with a loop.
Example
import java.awt.Graphics;
import java.awt.Polygon;
//from ww w . j a v a2 s . c o m
import javax.swing.JComponent;
import javax.swing.JFrame;
class MyCanvas extends JComponent {
public void paint(Graphics g) {
Polygon p = new Polygon();
for (int i = 0; i < 5; i++)
p.addPoint((int) (100 + 50 * Math.cos(i * 2 * Math.PI / 5)),
(int) (100 + 50 * Math.sin(i * 2 * Math.PI / 5)));
g.drawPolygon(p);
}
}
public class Main {
public static void main(String[] a) {
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setBounds(30, 30, 450, 450);
window.getContentPane().add(new MyCanvas());
window.setVisible(true);
}
}
The code above generates the following result.