1import java.awt.*;
2import java.awt.font.*;
3import java.awt.geom.*;
4import javax.swing.*;
5
6
7
8
9
10
11public class Chart extends JApplet
12{
13 public void init()
14 {
15 EventQueue.invokeLater(new Runnable()
16 {
17 public void run()
18 {
19 String v = getParameter("values");
20 if (v == null) return;
21 int n = Integer.parseInt(v);
22 double[] values = new double[n];
23 String[] names = new String[n];
24 for (int i = 0; i < n; i++)
25 {
26 values[i] = Double.parseDouble(getParameter("value." + (i + 1)));
27 names[i] = getParameter("name." + (i + 1));
28 }
29
30 add(new ChartComponent(values, names, getParameter("title")));
31 }
32 });
33 }
34}
35
36
37
38
39class ChartComponent extends JComponent
40{
41
42
43
44
45
46
47 public ChartComponent(double[] v, String[] n, String t)
48 {
49 values = v;
50 names = n;
51 title = t;
52 }
53
54 public void paintComponent(Graphics g)
55 {
56 Graphics2D g2 = (Graphics2D) g;
57
58
59 if (values == null) return;
60 double minValue = 0;
61 double maxValue = 0;
62 for (int i = 0; i < values.length; ++i)
63 {
64 double v = values[i];
65 if (minValue > v) minValue = v;
66 if (maxValue < v) maxValue = v;
67 }
68 if (maxValue == minValue) return;
69
70 int panelWidth = getWidth();
71 int panelHeight = getHeight();
72
73 Font titleFont = new Font("SansSerif", Font.BOLD, 20);
74 Font labelFont = new Font("SansSerif", Font.PLAIN, 10);
75
76
77 FontRenderContext context = g2.getFontRenderContext();
78 Rectangle2D titleBounds = titleFont.getStringBounds(title, context);
79
80 double titleWidth = titleBounds.getWidth();
81 double top = titleBounds.getHeight();
82
83
84 double y = -titleBounds.getY();
85 double x = (panelWidth - titleWidth) / 2;
86 g2.setFont(titleFont);
87 g2.drawString(title, (float) x, (float) y);
88
89
90 LineMetrics labelMetrics = labelFont.getLineMetrics("", context);
91 double bottom = labelMetrics.getHeight();
92
93 y = panelHeight - labelMetrics.getDescent();
94 g2.setFont(labelFont);
95
96
97 double scale = (panelHeight - top - bottom) / (maxValue - minValue);
98 int barWidth = panelWidth / values.length;
99
100
101 for (int i = 0; i < values.length; ++i)
102 {
103
104 double x1 = i * barWidth + 1;
105 double y1 = top;
106 double height = values[i] * scale;
107 if (values[i] >= 0) y1 += (maxValue - values[i]) * scale;
108 else
109 {
110 y1 += maxValue * scale;
111 height = -height;
112 }
113
114
115 Rectangle2D rect = new Rectangle2D.Double(x1, y1, barWidth - 2, height);
116 g2.setPaint(Color.RED);
117 g2.fill(rect);
118 g2.setPaint(Color.BLACK);
119 g2.draw(rect);
120
121
122 Rectangle2D labelBounds = labelFont.getStringBounds(names[i], context);
123
124 double labelWidth = labelBounds.getWidth();
125 x = x1 + (barWidth - labelWidth) / 2;
126 g2.drawString(names[i], (float) x, (float) y);
127 }
128 }
129
130 private double[] values;
131 private String[] names;
132 private String title;
133}