Java Reference
In-Depth Information
(x, y)
x is
xCenter
radius
cos(2
/6)
y is
yCenter
radius
sin(2
/6)
2
6
radius
(xCenter, yCenter)
F
IGURE
13.15
The program uses the
drawPolygon
method to draw a hexagon.
L
ISTING
13.5
DrawPolygon.java
1
import
javax.swing.JFrame;
2
import
javax.swing.JPanel;
3
import
java.awt.Graphics;
4
import
java.awt.Polygon;
5
6
public class
DrawPolygon
extends
JFrame {
7
public
DrawPolygon() {
8 setTitle(
"DrawPolygon"
);
9 add(
new
PolygonsPanel());
10 }
11
12
/** Main method */
13
public static void
main(String[] args) {
14 DrawPolygon frame =
new
DrawPolygon();
15 frame.setSize(
200
,
250
);
16 frame.setLocationRelativeTo(
null
);
// Center the frame
17 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
18 frame.setVisible(
true
);
19 }
20 }
21
22
// Draw a polygon in the panel
23
class
PolygonsPanel
extends
JPanel {
24 @Override
25
add a panel
protected void
paintComponent(Graphics g)
{
paintComponent
26
27
28
super
.paintComponent(g);
int
xCenter = getWidth() /
2
;
29
int
yCenter = getHeight() /
2
;
30
int
radius = (
int
)(Math.min(getWidth(), getHeight()) *
0.4
);
31
32
// Create a Polygon object
33 Polygon polygon =
new
Polygon();
34
35
// Add points to the polygon in this order
36 (xCenter + radius, yCenter);
37 ((
int
)(xCenter + radius *
38 Math.cos(
2
* Math.PI /
6
)), (
int
)(yCenter - radius *
39 Math.sin(
2
* Math.PI /
6
)));
40 polygon.addPoint((
int
)(xCenter + radius *
41 Math.cos(
2
*
2
* Math.PI /
6
)), (
int
)(yCenter - radius *
42 Math.sin(
2
*
2
* Math.PI /
6
)));
43 polygon.addPoint((
int
)(xCenter + radius *
44 Math.cos(
3
*
2
* Math.PI /
6
)), (
int
)(yCenter - radius *
45 Math.sin(
3
*
2
* Math.PI /
6
)));
polygon.addPoint
add a point
polygon.addPoint