Java Reference
In-Depth Information
Method
Description
Polygon
constructors and methods
public
Polygon()
Constructs a new polygon object. The polygon does not contain any points.
public
Polygon(
int
[] xValues,
int
[] yValues,
int
numberOfPoints)
Constructs a new polygon object. The polygon has
numberOfPoints
sides,
with each point consisting of an
x
-coordinate from
xValues
and a
y
-coordi-
nate from
yValues
.
public void
addPoint(
int
x,
int
y)
Adds pairs of
x
- and
y
-coordinates to the
Polygon
.
Fig. 13.26
|
Graphics
methods for polygons and class
Polygon
methods. (Part 2 of 2.)
1
// Fig. 13.27: PolygonsJPanel.java
2
// Drawing polygons.
3
import
java.awt.Graphics;
4
5
import
java.awt.Polygon;
import
javax.swing.JPanel;
6
7
public
class
PolygonsJPanel
extends
JPanel
8
{
9
// draw polygons and polylines
10
@Override
11
public
void
paintComponent(Graphics g)
12
{
13
super
.paintComponent(g);
14
15
// draw polygon with Polygon object
int
[] xValues = {
20
,
40
,
50
,
30
,
20
,
15
};
int
[] yValues = {
50
,
50
,
60
,
80
,
80
,
60
};
Polygon polygon1 =
new
Polygon(xValues, yValues,
6
);
g.drawPolygon(polygon1);
16
17
18
19
20
21
// draw polylines with two arrays
int
[] xValues2 = {
70
,
90
,
100
,
80
,
70
,
65
,
60
};
int
[] yValues2 = {
100
,
100
,
110
,
110
,
130
,
110
,
90
};
g.drawPolyline(xValues2, yValues2,
7
);
22
23
24
25
26
// fill polygon with two arrays
int
[] xValues3 = {
120
,
140
,
150
,
190
};
int
[] yValues3 = {
40
,
70
,
80
,
60
};
g.fillPolygon(xValues3, yValues3,
4
);
27
28
29
30
31
// draw filled polygon with Polygon object
Polygon polygon2 =
new
Polygon();
polygon2.addPoint(
165
,
135
);
polygon2.addPoint(
175
,
150
);
polygon2.addPoint(
270
,
200
);
32
33
34
35
Fig. 13.27
|
Polygons displayed with
drawPolygon
and
fillPolygon
. (Part 1 of 2.)