**How to draw Polygons in java?**

In Java rectangles are defined through the position of their upper left hand corner, their height, and their width. Therefore it is implicitly supposed that there is in fact an upper left hand corner. Not all rectangles have an upper left hand corner. For example consider the rectangle below.

Where is its upper left hand corner? What's been supposed so far is that the sides of the rectangle are parallel to the coordinate axes. You can't yet handle a rectangle which been rotated at an arbitrary angle.

There are a few other things you can't handle either, triangles, rhombuses, stars, kites, octagons and more. For take care of this broad class of shapes Java has a Polygon class.

Polygons are defined through their corners. No assumptions are made about them except in which they lie in a 2-D plane. The primary constructor for the Polygon class is

public Polygon(int[] xpoints, int[] ypoints, int npoints)

xpoints is an array which contains the x coordinates of the polygon. ypoints is an array in which contains the y coordinates. Both should have the length npoints. Therefore to construct a 3-4-5 right triangle along with the right angle on the origin you would type

int[] xpoints = {0, 3, 0};

int[] ypoints = {0, 0, 4};

Polygon myTriangle = new Polygon(xpoints, ypoints, 3);

To in fact draw the polygon you use java.awt.Graphics's drawPolygon(Polygon p) method inside your paint() techniques like this:

g.drawPolygon(myTriangle);

You could pass the arrays and number of points directly to the drawPolygon() method if you prefer:

g.drawPolygon(xpoints, ypoints, xpoints.length);

There's also an overloaded fillPolygon() method. The syntax is exactly as you expect:

g.fillPolygon(myTriangle);

g.fillPolygon(xpoints, ypoints, xpoints.length());

nt rectLeft = appletWidth/2 - i*appletWidth/16;

int rectTop = appletHeight/2 - i*appletHeight/16;

g.fillOval(rectLeft, rectTop, rectWidth, rectHeight);

}

}

}

The .class file that draws this image is only 684 bytes. The equivalent GIF image is 1,850 bytes, almost three times larger.

Almost all the work in this applet consists of centering the enclosing rectangles within the applet. The lines in bold do that. The first two lines just set the height and the width of the rectangle to the suitable fraction of the applet's height and width. The further two lines set the position of the upper left hand corner. Once the rectangle is positioned, drawing the oval is simple.