Java Reference
In-Depth Information
Listing 13.4 is an example of how to draw arcs; the output is shown in Figure 13.11.
L
ISTING
13.4
DrawArcs.java
1
import
javax.swing.JFrame;
2
import
javax.swing.JPanel;
3
import
java.awt.Graphics;
4
5
public class
DrawArcs
extends
JFrame {
6
public
DrawArcs() {
7 setTitle(
"DrawArcs"
);
8 add(
new
ArcsPanel());
9 }
10
11
/** Main method */
12
public static void
main(String[] args) {
13 DrawArcs frame =
new
DrawArcs();
14 frame.setSize(
250
,
300
);
15 frame.setLocationRelativeTo(
null
);
// Center the frame
16 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
17 frame.setVisible(
true
);
18 }
19 }
20
21
// The class for drawing arcs on a panel
22
class
ArcsPanel
extends
JPanel {
23 @Override
// Draw four blades of a fan
24
add a panel
protected void
paintComponent(Graphics g)
{
override
paintComponent
25
26
27
super
.paintComponent(g);
int
xCenter = getWidth() /
2
;
28
int
yCenter = getHeight() /
2
;
29
int
radius = (
int
)(Math.min(getWidth(), getHeight()) *
0.4
);
30
31
int
x = xCenter - radius;
32
int
y = yCenter - radius;
33
34
35
36
37
38 }
39 }
g.fillArc(x, y,
2
* radius,
2
* radius,
0
,
30
);
30° arc from 0°
g.fillArc(x, y,
2
* radius,
2
* radius,
90
,
30
);
30° arc from 90°
30° arc from 180°
30° arc from 270°
g.fillArc(x, y,
2
* radius,
2
* radius,
180
,
30
);
g.fillArc(x, y,
2
* radius,
2
* radius,
270
,
30
);
(x, y)
30
F
IGURE
13.11
The program draws four filled arcs.