Java Reference
In-Depth Information
Here is an example of creating a polygon and adding points into it:
Polygon polygon =
new
Polygon();
polygon.addPoint(
40
,
20
);
polygon.addPoint(
70
,
40
);
polygon.addPoint(
60
,
80
);
polygon.addPoint(
45
,
45
);
polygon.addPoint(
20
,
60
);
After these points are added,
xpoints
is {
40
,
70
,
60
,
45
,
20
},
ypoints
is {
20
,
40
,
80
,
45
,
60
}, and
npoints
is
5
.
xpoints
,
ypoints
, and
npoints
are public data fields in
Polygon
, which is a bad design. If the user changes a
Polygon
's
npoints
data field without
properly changing its
xpoints
and
ypoints
data fields, this will cause inconsistent data in
the
Polygon
object.
To draw or fill a polygon, use one of the following methods in the
Graphics
class:
drawPolygon(Polygon polygon);
fillPolygon(Polygon polygon);
drawPolygon(
int
[] xpoints,
int
[] ypoints,
int
npoints);
fillPolygon(
int
[] xpoints,
int
[] ypoints,
int
npoints);
For example:
int
x[] = {
40
,
70
,
60
,
45
,
20
};
int
y[] = {
20
,
40
,
80
,
45
,
60
};
g.drawPolygon(x, y, x.length);
The drawing method opens the polygon by drawing lines between point
(x[i], y[i])
and
point
(x[i+1], y[i+1])
for
i = 0, ... , x.length-1
; it closes the polygon by draw-
ing a line between the first and last points (see Figure 13.14a).
(x[0], y[0])
(x[0], y[0])
(x[1], y[1])
(x[1], y[1])
(x[3], y[3])
(x[3], y[3])
(x[4], y[4])
(x[4], y[4])
(x[2], y[2])
(x[2], y[2])
(a) Polygon
(b) Polyline
F
IGURE
13.14
The
drawPolygon
method draws a polygon, and the
drawPolyLine
method draws a polyline.
To draw a polyline, use the
drawPolyline(int[] x, int[] y, int nPoints)
method, which draws a sequence of connected lines defined by arrays of
x-
and
y-
coordinates.
For example, the following code draws the polyline like the one shown in Figure 13.14b.
int
x[] = {
40
,
70
,
60
,
45
,
20
};
int
y[] = {
20
,
40
,
80
,
45
,
60
};
g.drawPolyline(x, y, x.length);
Listing 13.5 is an example of how to draw a hexagon, with the output shown in Figure 13.15.