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

Slanted rectangle

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

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

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

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

xpoints is an array that contains the x coordinates of the polygon. ypoints is an array that contains the y coordinates. Both should have the length npoints. Thus to construct a 3-4-5 right triangle 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 actually draw the polygon you use java.awt.Graphics's drawPolygon(Polygon p) method within your paint() method like this:


You can 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(xpoints, ypoints, xpoints.length());

Previous | Next | Top | Cafe au Lait

Copyright 1997, 1998, 2001 Elliotte Rusty Harold
Last Modified June 26, 2001