import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Polygon;
public class DrawPolygon extends JFrame {
public DrawPolygon() {
add(new PolygonPanel());
}
/** Main method */
public static void main(String[] args) {
DrawPolygon frame = new DrawPolygon();
frame.setTitle("DrawPolygon");
frame.setSize(300, 200);
frame.setLocationRelativeTo(null); //Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
//Draw a polygon in the panel
class PolygonPanel extends JPanel {
protected void paintComponent(Graphics g) {
int xCenter = getWidth() / 2;
int yCenter = getHeight() / 2;
int radius = Math.min(getWidth(), getHeight()) / 2;
int[] xPoints = new int[6];
int[] yPoints = new int[6];
int nPoints = 6;
for(int i = 0; i < nPoints; i++) {
xPoints[i] = (int)(xCenter + radius * Math.cos(Math.PI / 3 * i));
yPoints[i] = (int)(yCenter + radius * Math.sin(Math.PI / 3 * i));
}
// Create a Polygon object
Polygon polygon = new Polygon(xPoints, yPoints, nPoints);
super.paintComponent(g);
// Draw the polygon
g.setColor(Color.RED);
g.drawPolygon(polygon);
}
}
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Polygon;
public class DrawPolygon extends JFrame {
public DrawPolygon() {
add(new PolygonPanel());
}
/** Main method */
public static void main(String[] args) {
DrawPolygon frame = new DrawPolygon();
frame.setTitle("DrawPolygon");
frame.setSize(300, 200);
frame.setLocationRelativeTo(null); //Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
//Draw a polygon in the panel
class PolygonPanel extends JPanel {
protected void paintComponent(Graphics g) {
int xCenter = getWidth() / 2;
int yCenter = getHeight() / 2;
int radius = Math.min(getWidth(), getHeight()) / 2;
int[] xPoints = new int[6];
int[] yPoints = new int[6];
int nPoints = 6;
for(int i = 0; i < nPoints; i++) {
xPoints[i] = (int)(xCenter + radius * Math.cos(Math.PI / 3 * i));
yPoints[i] = (int)(yCenter + radius * Math.sin(Math.PI / 3 * i));
}
// Create a Polygon object
Polygon polygon = new Polygon(xPoints, yPoints, nPoints);
super.paintComponent(g);
// Draw the polygon
g.setColor(Color.RED);
g.drawPolygon(polygon);
}
}