A polygon is a closed geometrical figure which can have any number of sides. A polygon can be drawn by using the drawPolygon () method. This method takes three parameters.
The general form of the drawPolygon () method is:
void drawPolygon (int a [], int b [], int n)
where,
a [ ] is the array of integers having x-coordinates
b [ ] is the array of integers having y-coordinates
n is the total number of coordinate points required to draw a polygon.
Here is the java code for the program AppletDrawPolygon :.
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class AppletDrawPolygon extends Applet
{
public static void main(String[] args)
{
Frame OvalApplet = new Frame("Drawing Polygons in Applet Window Example");
OvalApplet.setSize(350, 250);
Applet AppletDrawPolygon = new AppletDrawPolygon();
OvalApplet.add(AppletDrawPolygon);
OvalApplet.setVisible(true);
OvalApplet.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0); } });
}
public void paint(Graphics g)
{
g.setColor(Color.darkGray);
g.setFont(new Font("Arial",Font.BOLD,14));
g.drawString("Drawing Polygons in Applet Window Example", 15, 40);
g.setFont(new Font("Arial",Font.BOLD,10));
g.drawString("http://ecomputernotes.com", 200, 205);
//set color to lightgreen
Color lightgreen = new Color(128, 255, 128);
g.setColor(lightgreen);
int PolygonCursor;
//Example: the (X_polygon,Y_polygon) points are (10, 70), (160, 70), (100, 115), (160, 160), (10, 160),(60, 115).
There are 6 sets of points, so we will place 6 in place of n.
int[] X_polygon = {10, 160, 100, 160, 10, 60};
int[] Y_polygon = {70,70, 115, 160, 160, 115};
//Syntax: drawPolygon(int[] xPoints, int[] yPoints, int numPoint);
g.drawPolygon (X_polygon, Y_polygon, 6);
PolygonCursor = 0;
while (PolygonCursor < 6)
{
X_polygon [PolygonCursor] = X_polygon [PolygonCursor] + 170;
PolygonCursor = PolygonCursor + 1;
}
//The Syntax for fillPolygon(int[] xPoints, int[] yPoints, int numPoint);
g.fillPolygon (X_polygon, Y_polygon, 6);
}
}