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:
g.drawPolygon(myTriangle);
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 a polymorphic fillPolygon()
method. The syntax is exactly as you expect:
g.fillPolygon(myTriangle);
g.fillPolygon(xpoints, ypoints, xpoints.length());