KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > BarChart


1 /*
2  * @(#)BarChart.java 1.18 06/02/22
3  *
4  * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions are met:
8  *
9  * -Redistribution of source code must retain the above copyright notice, this
10  * list of conditions and the following disclaimer.
11  *
12  * -Redistribution in binary form must reproduce the above copyright notice,
13  * this list of conditions and the following disclaimer in the documentation
14  * and/or other materials provided with the distribution.
15  *
16  * Neither the name of Sun Microsystems, Inc. or the names of contributors may
17  * be used to endorse or promote products derived from this software without
18  * specific prior written permission.
19  *
20  * This software is provided "AS IS," without a warranty of any kind. ALL
21  * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
22  * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
23  * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
24  * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
25  * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
26  * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
27  * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
28  * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
29  * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
30  * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
31  *
32  * You acknowledge that this software is not designed, licensed or intended
33  * for use in the design, construction, operation or maintenance of any
34  * nuclear facility.
35  */

36
37 /*
38  * @(#)BarChart.java 1.18 06/02/22
39  */

40
41 import java.awt.*;
42
43 /**
44  * A simple bar chart demo
45  * @version 1.6
46  * @author Sami Shaio
47  * @modified 06/21/00 Daniel Peek : refactored, comments
48  */

49 public class BarChart extends java.applet.Applet JavaDoc {
50     private static final int VERTICAL = 0;
51     private static final int HORIZONTAL = 1;
52
53     private static final int SOLID = 0;
54     private static final int STRIPED = 1;
55
56     private int orientation;
57     private String JavaDoc title;
58     private Font font;
59     private FontMetrics metrics;
60     private int fontHeight = 15;
61     private int columns;
62     private int values[];
63     private Color colors[];
64     private String JavaDoc labels[];
65     private int styles[];
66     private int scale = 10;
67     private int maxLabelWidth = 0;
68     private int barSpacing = 10;
69     private int maxValue = 0;
70
71     public void init() {
72   
73         getSettings();
74         
75         values = new int[columns];
76         labels = new String JavaDoc[columns];
77         styles = new int[columns];
78         colors = new Color[columns];
79
80         for (int i=0; i < columns; i++) {
81             parseValue(i);
82             parseLabel(i);
83             parseStyle(i);
84             parseColor(i);
85         }
86     }
87             
88     private void getSettings() {
89         font = new java.awt.Font JavaDoc("Monospaced", Font.BOLD, 12);
90         metrics = getFontMetrics(font);
91
92         title = getParameter("title");
93         if (title == null) {
94             title = "Chart";
95         }
96         
97         String JavaDoc temp = getParameter("columns");
98         if (temp == null) {
99             columns = 5;
100         } else {
101             columns = Integer.parseInt(temp);
102         }
103         
104         temp = getParameter("scale");
105         if (temp == null) {
106             scale = 10;
107         } else {
108             scale = Integer.parseInt(temp);
109         }
110
111         temp = getParameter("orientation");
112         if (temp == null) {
113             orientation = VERTICAL;
114         } else if (temp.equalsIgnoreCase("horizontal")) {
115             orientation = HORIZONTAL;
116         } else {
117             orientation = VERTICAL;
118         }
119     }
120
121     private void parseValue(int i) {
122         String JavaDoc temp = getParameter("C" + (i+1));
123         try {
124             values[i] = Integer.parseInt(temp);
125         } catch (NumberFormatException JavaDoc e) {
126             values[i] = 0;
127         } catch (NullPointerException JavaDoc e) {
128             values[i] = 0;
129         }
130         maxValue = Math.max(maxValue, values[i]);
131     }
132     
133     private void parseLabel(int i) {
134         String JavaDoc temp = getParameter("C" + (i+1) + "_label");
135         if (temp==null) {
136             labels[i] = "";
137         } else {
138             labels[i] = temp;
139         }
140         maxLabelWidth = Math.max(metrics.stringWidth
141                                  ((String JavaDoc) (labels[i])), maxLabelWidth);
142     }
143
144     private void parseStyle(int i) {
145         String JavaDoc temp = getParameter("C" + (i+1) + "_style");
146         if (temp == null || temp.equalsIgnoreCase("solid")) {
147             styles[i] = SOLID;
148         } else if (temp.equalsIgnoreCase("striped")) {
149             styles[i] = STRIPED;
150         } else {
151             styles[i] = SOLID;
152         }
153     }
154     
155     private void parseColor(int i) {
156         String JavaDoc temp = getParameter("C" + (i+1) + "_color");
157         if (temp != null) {
158             temp = temp.toLowerCase();
159             if (temp.equals("red")) {
160                 colors[i] = Color.red;
161             } else if (temp.equals("green")) {
162                 colors[i] = Color.green;
163             } else if (temp.equals("blue")) {
164                 colors[i] = Color.blue;
165             } else if (temp.equals("pink")) {
166                 colors[i] = Color.pink;
167             } else if (temp.equals("orange")) {
168                 colors[i] = Color.orange;
169             } else if (temp.equals("magenta")) {
170                 colors[i] = Color.magenta;
171             } else if (temp.equals("cyan")) {
172                 colors[i] = Color.cyan;
173             } else if (temp.equals("white")) {
174                 colors[i] = Color.white;
175             } else if (temp.equals("yellow")) {
176                 colors[i] = Color.yellow;
177             } else if (temp.equals("gray")) {
178                 colors[i] = Color.gray;
179             } else if (temp.equals("darkgray")) {
180                 colors[i] = Color.darkGray;
181             } else {
182                 colors[i] = Color.gray;
183             }
184         } else {
185             colors[i] = Color.gray;
186         }
187     }
188
189     public void paint(Graphics g) {
190         // draw the title centered at the bottom of the bar graph
191
g.setColor(Color.black);
192         g.setFont(font);
193         
194         g.drawRect(0, 0, getSize().width - 1, getSize().height - 1);
195
196         int titleWidth = metrics.stringWidth(title);
197         int cx = Math.max((getSize().width - titleWidth) / 2, 0);
198         int cy = getSize().height - metrics.getDescent();
199         g.drawString(title, cx, cy);
200
201         // draw the bars and their titles
202
if(orientation == HORIZONTAL) {
203             paintHorizontal(g);
204         } else { // VERTICAL
205
paintVertical(g);
206         }
207     }
208         
209     private void paintHorizontal(Graphics g) {
210         // x and y coordinates to draw/write to
211
int cx, cy;
212         int barHeight = metrics.getHeight();
213
214         for (int i = 0; i < columns; i++) {
215             
216             // set the X coordinate for this bar and label and center it
217
int widthOfItems = maxLabelWidth + 3 + (maxValue * scale) + 5
218                 + metrics.stringWidth(Integer.toString(maxValue));
219             cx = Math.max((getSize().width - widthOfItems) / 2, 0);
220             
221             // set the Y coordinate for this bar and label
222
cy = getSize().height - metrics.getDescent() - metrics.getHeight()
223                 - barSpacing - ((columns - i - 1) * (barSpacing + barHeight));
224
225             // draw the label
226
g.setColor(Color.black);
227             g.drawString(labels[i], cx, cy);
228             cx += maxLabelWidth + 3;
229
230         
231             // draw the shadow
232
g.fillRect(cx + 4, cy - barHeight + 4,
233                        (values[i] * scale), barHeight);
234
235             // draw the bar
236
g.setColor(colors[i]);
237             if (styles[i] == STRIPED) {
238                 for (int k = 0; k <= values[i] * scale; k += 2) {
239                     g.drawLine(cx + k, cy - barHeight, cx + k, cy);
240                 }
241             } else { // SOLID
242
g.fillRect(cx, cy - barHeight,
243                            (values[i] * scale) + 1, barHeight + 1);
244             }
245             cx += (values[i] * scale) + 4;
246             
247             // draw the value at the end of the bar
248
g.setColor(g.getColor().darker());
249             g.drawString(Integer.toString(values[i]), cx, cy);
250         }
251     }
252     
253     private void paintVertical(Graphics g) {
254         int barWidth = maxLabelWidth;
255
256         for (int i = 0; i < columns; i++) {
257
258             // X coordinate for this label and bar (centered)
259
int widthOfItems = (barWidth + barSpacing) * columns - barSpacing;
260             int cx = Math.max((getSize().width - widthOfItems) / 2, 0);
261             cx += (maxLabelWidth + barSpacing) * i;
262             
263             // Y coordinate for this label and bar
264
int cy = getSize().height - metrics.getHeight()
265                 - metrics.getDescent() - 4;
266
267             // draw the label
268
g.setColor(Color.black);
269             g.drawString(labels[i], cx, cy);
270             cy -= metrics.getHeight() - 3;
271
272             // draw the shadow
273
g.fillRect(cx + 4, cy - (values[i] * scale) - 4,
274                        barWidth, (values[i] * scale));
275             
276             // draw the bar
277
g.setColor(colors[i]);
278             if (styles[i] == STRIPED) {
279                 for (int k=0; k <= values[i] * scale; k+=2) {
280                     g.drawLine(cx, cy - k,
281                                cx + barWidth, cy - k);
282                 }
283             } else {
284                 g.fillRect(cx, cy - (values[i] * scale),
285                            barWidth + 1, (values[i] * scale) + 1);
286             }
287             cy -= (values[i] * scale) + 5;
288
289             // draw the value on top of the bar
290
g.setColor(g.getColor().darker());
291             g.drawString(Integer.toString(values[i]), cx, cy);
292         }
293     }
294     
295     public String JavaDoc getAppletInfo() {
296         return "Title: Bar Chart \n"
297             + "Author: Sami Shaio \n"
298             + "A simple bar chart demo.";
299     }
300     
301     public String JavaDoc[][] getParameterInfo() {
302         String JavaDoc[][] info = {
303             {"title", "string", "The title of bar graph. Default is 'Chart'"},
304             {"scale", "int", "The scale of the bar graph. Default is 10."},
305             {"columns", "int", "The number of columns/rows. Default is 5."},
306             {"orientation", "{VERTICAL, HORIZONTAL}",
307              "The orienation of the bar graph. Default is VERTICAL."},
308             {"c#", "int", "Subsitute a number for #. "
309              + "The value/size of bar #. Default is 0."},
310             {"c#_label", "string", "The label for bar #. "
311              + "Default is an empty label."},
312             {"c#_style", "{SOLID, STRIPED}", "The style of bar #. "
313              + "Default is SOLID."},
314             {"c#_color", "{RED, GREEN, BLUE, PINK, ORANGE, MAGENTA, CYAN, "
315              + "WHITE, YELLOW, GRAY, DARKGRAY}",
316              "The color of bar #. Default is GRAY."}
317         };
318         return info;
319     }
320 }
321
Popular Tags