1 import javax.swing.JFrame;
2 import javax.swing.JPanel;
3 import java.awt.Graphics;
4 import java.awt.Polygon;
5
6 public class DrawPolygon extends JFrame {
7 public DrawPolygon() {
8 setTitle("DrawPolygon");
9 add(new PolygonsPanel());
10 }
11
12
13 public static void main(String[] args) {
14 DrawPolygon frame = new DrawPolygon();
15 frame.setLocationRelativeTo(null);
16 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
17 frame.setSize(200, 250);
18 frame.setVisible(true);
19 }
20 }
21
22
23 class PolygonsPanel extends JPanel {
24 @Override
25 protected void paintComponent(Graphics g) {
26 super.paintComponent(g);
27
28 int xCenter = getWidth() / 2;
29 int yCenter = getHeight() / 2;
30 int radius = (int)(Math.min(getWidth(), getHeight()) * 0.4);
31
32
33 Polygon polygon = new Polygon();
34
35
36 polygon.addPoint(xCenter + radius, yCenter);
37 polygon.addPoint((int)(xCenter + radius *
38 Math.cos(2 * Math.PI / 6)), (int)(yCenter - radius *
39 Math.sin(2 * Math.PI / 6)));
40 polygon.addPoint((int)(xCenter + radius *
41 Math.cos(2 * 2 * Math.PI / 6)), (int)(yCenter - radius *
42 Math.sin(2 * 2 * Math.PI / 6)));
43 polygon.addPoint((int)(xCenter + radius *
44 Math.cos(3 * 2 * Math.PI / 6)), (int)(yCenter - radius *
45 Math.sin(3 * 2 * Math.PI / 6)));
46 polygon.addPoint((int)(xCenter + radius *
47 Math.cos(4 * 2 * Math.PI / 6)), (int)(yCenter - radius *
48 Math.sin(4 * 2 * Math.PI / 6)));
49 polygon.addPoint((int)(xCenter + radius *
50 Math.cos(5 * 2 * Math.PI / 6)), (int)(yCenter - radius *
51 Math.sin(5 * 2 * Math.PI / 6)));
52
53
54 g.drawPolygon(polygon);
55 }
56 }