1 |
import java.applet.Applet; |
2 |
import java.awt.Graphics; |
3 |
import java.awt.Graphics2D; |
4 |
import java.awt.geom.Line2D; |
5 |
|
6 |
/** |
7 |
This applet draws a chart of the average monthly |
8 |
temperatures in Phoenix, AZ. |
9 |
*/ |
10 |
public class ChartApplet extends Applet |
11 |
{ |
12 |
public void paint(Graphics g) |
13 |
{ |
14 |
Graphics2D g2 = (Graphics2D)g; |
15 |
|
16 |
month = 1; |
17 |
|
18 |
drawBar(g2, JAN_TEMP); |
19 |
drawBar(g2, FEB_TEMP); |
20 |
drawBar(g2, MAR_TEMP); |
21 |
drawBar(g2, APR_TEMP); |
22 |
drawBar(g2, MAY_TEMP); |
23 |
drawBar(g2, JUN_TEMP); |
24 |
drawBar(g2, JUL_TEMP); |
25 |
drawBar(g2, AUG_TEMP); |
26 |
drawBar(g2, SEP_TEMP); |
27 |
drawBar(g2, OCT_TEMP); |
28 |
drawBar(g2, NOV_TEMP); |
29 |
drawBar(g2, DEC_TEMP); |
30 |
} |
31 |
|
32 |
/** |
33 |
Draws a bar for the current month and increments |
34 |
the month. |
35 |
@param g2 the graphics context |
36 |
@param temperature the temperature for the month |
37 |
*/ |
38 |
public void drawBar(Graphics2D g2, int temperature) |
39 |
{ |
40 |
Line2D.Double bar |
41 |
= new Line2D.Double(xpixel(month), ypixel(0), |
42 |
xpixel(month), ypixel(temperature)); |
43 |
|
44 |
g2.draw(bar); |
45 |
|
46 |
month++; |
47 |
} |
48 |
|
49 |
/** |
50 |
Converts from user coordinates to pixel coordinates |
51 |
@param xuser an x-value in user coordinates |
52 |
@return the corresponding value in pixel coordinates |
53 |
*/ |
54 |
public double xpixel(double xuser) |
55 |
{ |
56 |
return (xuser - XMIN) * (getWidth() - 1) / (XMAX - XMIN); |
57 |
} |
58 |
|
59 |
/** |
60 |
Converts from user coordinates to pixel coordinates |
61 |
@param yuser a y-value in user coordinates |
62 |
@return the corresponding value in pixel coordinates |
63 |
*/ |
64 |
public double ypixel(double yuser) |
65 |
{ |
66 |
return (yuser - YMAX) * (getHeight() - 1) / (YMIN - YMAX); |
67 |
} |
68 |
|
69 |
private static final int JAN_TEMP = 11; |
70 |
private static final int FEB_TEMP = 13; |
71 |
private static final int MAR_TEMP = 16; |
72 |
private static final int APR_TEMP = 20; |
73 |
private static final int MAY_TEMP = 25; |
74 |
private static final int JUN_TEMP = 31; |
75 |
private static final int JUL_TEMP = 33; |
76 |
private static final int AUG_TEMP = 32; |
77 |
private static final int SEP_TEMP = 29; |
78 |
private static final int OCT_TEMP = 23; |
79 |
private static final int NOV_TEMP = 16; |
80 |
private static final int DEC_TEMP = 12; |
81 |
|
82 |
private static final double XMIN = 1; |
83 |
private static final double XMAX = 12; |
84 |
private static final double YMIN = 0; |
85 |
private static final double YMAX = 40; |
86 |
|
87 |
private int month; |
88 |
} |
89 |
|
90 |
|