1、餅圖、柱狀圖、折線圖生成的工具類
1 package com.text.util;
2
3 import java.awt.BasicStroke;
4 import java.awt.Color;
5 import java.awt.Font;
6 import java.awt.GradientPaint;
7 import java.io.IOException;
8 import java.text.DecimalFormat;
9 import java.text.NumberFormat;
10 import java.text.SimpleDateFormat;
11
12 import javax.servlet.http.HttpServletRequest;
13 import javax.servlet.http.HttpSession;
14
15 import org.jfree.chart.ChartFactory;
16 import org.jfree.chart.JFreeChart;
17 import org.jfree.chart.axis.CategoryAxis;
18 import org.jfree.chart.axis.DateAxis;
19 import org.jfree.chart.axis.ValueAxis;
20 import org.jfree.chart.labels.ItemLabelAnchor;
21 import org.jfree.chart.labels.ItemLabelPosition;
22 import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
23 import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
24 import org.jfree.chart.labels.StandardPieToolTipGenerator;
25 import org.jfree.chart.labels.StandardXYItemLabelGenerator;
26 import org.jfree.chart.labels.StandardXYToolTipGenerator;
27 import org.jfree.chart.plot.CategoryPlot;
28 import org.jfree.chart.plot.IntervalMarker;
29 import org.jfree.chart.plot.PiePlot;
30 import org.jfree.chart.plot.PlotOrientation;
31 import org.jfree.chart.plot.XYPlot;
32 import org.jfree.chart.renderer.category.BarRenderer;
33 import org.jfree.chart.renderer.category.BarRenderer3D;
34 import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
35 import org.jfree.chart.servlet.ServletUtilities;
36 import org.jfree.chart.title.LegendTitle;
37 import org.jfree.chart.title.TextTitle;
38 import org.jfree.data.category.CategoryDataset;
39 import org.jfree.data.general.DefaultPieDataset;
40 import org.jfree.data.time.TimeSeriesCollection;
41 import org.jfree.ui.Layer;
42 import org.jfree.ui.TextAnchor;
43 import org.jfree.util.Rotation;
44
45 /**
46 *<br> 文 件 名:JFreeChartServlet.java
47 *<br> 包 名:com.report.servlet
48 *<br> 創 建 人:
49 *<br> 創建日期: Mar 30, 2010 1:00:23 PM
50 *<br> 描 述:生成jFreeChart
51 */
52 public class JFreeChartCreater {
53
54 /**
55 *<br> 方法名稱:createPieChart
56 *<br> 功能描述:創建PieChart(餅圖)圖表
57 *<br> 返 回 值:JFreeChart
58 *<br> 創 建 人:
59 *<br> 創建日期:Mar 30, 2010 12:59:07 PM
60 *@param dataset
61 */
62 public static JFreeChart createPieChart(DefaultPieDataset dataset,
63 String title,boolean is3D) {
64 JFreeChart chart=null;
65 if(is3D){
66 chart=ChartFactory.createPieChart3D(
67 title, // 圖表標題
68 dataset, // 數據集
69 true, // 是否顯示圖例
70 true, // 是否顯示工具提示
71 true // 是否生成URL
72 );
73 }
74 else{ chart = ChartFactory.createPieChart(
75 title, // 圖表標題
76 dataset, // 數據集
77 true, // 是否顯示圖例
78 true, // 是否顯示工具提示
79 true // 是否生成URL
80 );
81 }
82 // 設置標題字體,為了防止中文亂碼:必須設置字體
83 chart.setTitle(new TextTitle(title, new Font("黑體", Font.ITALIC, 22)));
84 // 設置圖例的字體,為了防止中文亂碼:必須設置字體
85 chart.getLegend().setItemFont(new Font("黑體", Font.BOLD, 12));
86 // 獲取餅圖的Plot對象(實際圖表)
87 PiePlot plot = (PiePlot) chart.getPlot();
88 // 圖形邊框顏色
89 plot.setBaseSectionOutlinePaint(Color.GRAY);
90 // 圖形邊框粗細
91 plot.setBaseSectionOutlineStroke(new BasicStroke(0.0f));
92 // 設置餅狀圖的繪制方向,可以按順時針方向繪制,也可以按逆時針方向繪制
93 plot.setDirection(Rotation.ANTICLOCKWISE);
94 // 設置繪制角度(圖形旋轉角度)
95 plot.setStartAngle(70);
96 // 設置突出顯示的數據塊
97 // plot.setExplodePercent("One", 0.1D);
98 // 設置背景色透明度
99 plot.setBackgroundAlpha(0.7F);
100 // 設置前景色透明度
101 plot.setForegroundAlpha(0.65F);
102 // 設置區塊標簽的字體==為了防止中文亂碼:必須設置字體
103 plot.setLabelFont(new Font("宋體", Font.PLAIN, 12));
104 // 扇區分離顯示,對3D圖不起效
105 if(is3D)
106 plot.setExplodePercent(dataset.getKey(3), 0.1D);
107 // 圖例顯示百分比:自定義方式,{0} 表示選項, {1} 表示數值, {2} 表示所占比例 ,小數點后兩位
108 plot.setLabelGenerator(new StandardPieSectionLabelGenerator(
109 "{0}:{1}\r\n({2})", NumberFormat.getNumberInstance(),
110 new DecimalFormat("0.00%")));
111 // 指定顯示的餅圖為:圓形(true) 還是橢圓形(false)
112 plot.setCircular(true);
113 // 沒有數據的時候顯示的內容
114 plot.setNoDataMessage("找不到可用數據
");
115
116 // 設置鼠標懸停提示
117 plot.setToolTipGenerator(new StandardPieToolTipGenerator());
118 // 設置熱點鏈接
119 // plot.setURLGenerator(new StandardPieURLGenerator("detail.jsp"));
120
121 return chart;
122 }
123 /**
124 *<br> 方法名稱:createPieChart
125 *<br> 功能描述:創建BarChart(柱狀圖/條形圖)圖表
126 *<br> 返 回 值:JFreeChart
127 *<br> 創 建 人:
128 *<br> 創建日期:Mar 30, 2010 12:59:07 PM
129 *@param dataset
130 */
131 @SuppressWarnings("deprecation")
132 public static JFreeChart createBarChart(CategoryDataset dataset,
133 String title, String x, String y,boolean is3D) {
134 JFreeChart chart =null;
135 BarRenderer renderer = null;
136 if(is3D){
137 chart = ChartFactory.createBarChart3D( // 3D柱狀圖
138 // JFreeChart chart = ChartFactory.createLineChart3D( //3D折線圖
139 title, // 圖表的標題
140 x, // 目錄軸的顯示標簽
141 y, // 數值軸的顯示標簽
142 dataset, // 數據集
143 PlotOrientation.VERTICAL, // 圖表方式:V垂直;H水平
144 true, // 是否顯示圖例
145 false, // 是否顯示工具提示
146 false // 是否生成URL
147 );
148 // 柱圖的呈現器
149 renderer = new BarRenderer3D();
150 renderer.setItemLabelGenerator(new StandardCategoryItemLabelGenerator());
151 renderer.setItemLabelFont(new Font("黑體",Font.PLAIN,12));
152 renderer.setItemLabelsVisible(true);
153 //3D柱子上不能正常顯示數字
154 //注意:如果數值太大切前面的柱子低于后面的柱子,那么前面的那個數值將被擋住,所以將下面方法中的0該為-值
155 ItemLabelPosition itemLabelPositionFallback = new ItemLabelPosition(
156 ItemLabelAnchor.OUTSIDE12,TextAnchor.BASELINE_LEFT,
157 TextAnchor.HALF_ASCENT_LEFT,-1.3D);
158 //設置不能正常顯示的柱子label的position
159 renderer.setPositiveItemLabelPositionFallback(itemLabelPositionFallback);
160 renderer.setNegativeItemLabelPositionFallback(itemLabelPositionFallback);
161 }else{
162 chart = ChartFactory.createBarChart( // 柱狀圖
163 // JFreeChart chart = ChartFactory.createLineChart3D( //3D折線圖
164 title, // 圖表的標題
165 x, // 目錄軸的顯示標簽
166 y, // 數值軸的顯示標簽
167 dataset, // 數據集
168 PlotOrientation.VERTICAL, // 圖表方式:V垂直;H水平
169 true, // 是否顯示圖例
170 false, // 是否顯示工具提示
171 false // 是否生成URL
172 );
173 // 柱圖的呈現器
174 renderer = new BarRenderer();
175 renderer.setIncludeBaseInRange(true); // 顯示每個柱的數值,并修改該數值的字體屬性
176 renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
177 renderer.setBaseItemLabelsVisible(true);
178 }
179
180 //設置圖片背景
181 // chart.setBackgroundPaint(Color.PINK);
182 // 為了防止中文亂碼:必須設置字體
183 chart.setTitle(new TextTitle(title, new Font("黑體", Font.PLAIN, 22)));
184 LegendTitle legend = chart.getLegend(); // 獲取圖例
185 legend.setItemFont(new Font("宋體", Font.BOLD, 12)); // 設置圖例的字體,防止中文亂碼
186 CategoryPlot plot = (CategoryPlot) chart.getPlot(); // 獲取柱圖的Plot對象(實際圖表)
187 // 設置柱圖背景色(注意,系統取色的時候要使用16位的模式來查看顏色編碼,這樣比較準確)
188 plot.setBackgroundPaint(new Color(255, 255, 204));
189 plot.setForegroundAlpha(0.65F); // 設置前景色透明度
190 // 設置橫虛線可見
191 plot.setRangeGridlinesVisible(true);
192 // 虛線色彩
193 plot.setRangeGridlinePaint(Color.gray);
194
195 ValueAxis rangeAxis = plot.getRangeAxis();
196 //設置最高的一個Item與圖片頂端的距離
197 rangeAxis.setUpperMargin(0.2);
198 //設置最低的一個Item與圖片底端的距離
199 rangeAxis.setLowerMargin(0.3);
200
201 CategoryAxis domainAxis = plot.getDomainAxis(); // 獲取x軸
202 domainAxis.setMaximumCategoryLabelWidthRatio(1.0f);// 橫軸上的 Lable 是否完整顯示
203 domainAxis.setLabelFont(new Font("宋體", Font.TRUETYPE_FONT, 14));// 設置字體,防止中文亂碼
204 domainAxis.setTickLabelFont(new Font("宋體", Font.BOLD, 12));// 軸數值
205 // h.setCategoryLabelPositions(CategoryLabelPositions.UP_45);//45度傾斜
206 plot.getRangeAxis().setLabelFont(new Font("宋體", Font.TRUETYPE_FONT, 14)); // Y軸設置字體,防止中文亂碼
207
208 renderer.setBaseOutlinePaint(Color.BLACK); // 設置柱子邊框顏色
209 renderer.setDrawBarOutline(true); // 設置柱子邊框可見
210 renderer.setSeriesPaint(0, Color.YELLOW); // 設置每個柱的顏色
211 renderer.setSeriesPaint(1, Color.green);
212 renderer.setSeriesPaint(2, Color.RED);
213 renderer.setSeriesPaint(3, Color.CYAN);
214 renderer.setSeriesPaint(5, Color.ORANGE);
215 renderer.setSeriesPaint(4, Color.MAGENTA);
216 renderer.setSeriesPaint(6, Color.DARK_GRAY);
217 renderer.setSeriesPaint(7, Color.PINK);
218 renderer.setSeriesPaint(8, Color.black);
219 renderer.setItemMargin(0.1); // 設置每個地區所包含的平行柱的之間距離
220 plot.setRenderer(renderer); // 給柱圖添加呈現器
221 plot.setForegroundAlpha(0.7f); // 設置柱的透明度
222 // renderer.setMaximumBarWidth(0.2); // 設置柱子寬度
223 // renderer.setMinimumBarLength(0.6); // 設置柱子高度
224 //設置橫坐標顯示位置(默認是下方);
225 // plot.setDomainAxisLocation(AxisLocation.TOP_OR_RIGHT);
226 //設置縱坐標顯示位置(默認是左方)
227 // plot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_RIGHT);
228 // 沒有數據的時候顯示的內容
229 plot.setNoDataMessage("找不到可用數據
");
230
231 return chart;
232 }
233
234 /**
235 *<br> 方法名稱:JFreeChartSeriesChart
236 *<br> 功能描述:創建曲線圖(折線圖)
237 *<br> 注意事項:一般曲線圖不用加域所以后4個參數一般為(false,null,0,0)
238 *<br> 參 數:title-標題;subtitleStr-子標題;domain-x軸標志;range-y軸標志;dataset-設置數據;isAreaText-是否在圖標中加域;
239 *<br> areaText-域中文字,lowpress-域的最低刻度;uperpress-域的最高刻度
240 *<br> 返 回 值:JFreeChart
241 *<br> 創 建 人:
242 *<br> 創建日期:Mar 30, 2010 1:11:24 PM
243 */
244 @SuppressWarnings("deprecation")
245 public static JFreeChart JFreeChartSeriesChart(String title,
246 String subtitleStr, String domain, String range,
247 TimeSeriesCollection dataset,boolean isAreaText,String areaText,double lowpress,double uperpress) { //時間曲線元素
248 // JFreeChart chart = ChartFactory.createTimeSeriesChart("標題","x軸標志","y軸標志","設置數據",是否顯示圖形,是否進行提示,是否配置報表存放地址);
249 JFreeChart chart = ChartFactory.createTimeSeriesChart(title, domain,range, dataset, true, true, false);
250
251 if(subtitleStr!=null){
252 TextTitle subtitle = new TextTitle(subtitleStr, new Font("黑體",Font.BOLD, 12));
253 chart.addSubtitle(subtitle);
254 }
255 // 設置日期顯示格式
256 XYPlot plot = chart.getXYPlot();
257 DateAxis axis = (DateAxis) plot.getDomainAxis();
258 axis.setDateFormatOverride(new SimpleDateFormat("yyyy-MM-dd"));
259 // 設置標題的顏色
260 chart.setTitle(new TextTitle(title, new Font("黑體", Font.ITALIC, 22)));
261 chart.setBackgroundPaint(new GradientPaint(0, 0, Color.white, 0, 1000, Color.blue));
262 plot.setOutlineStroke(new BasicStroke(1.5f)); // 邊框粗細
263 ValueAxis vaxis = plot.getDomainAxis();
264 vaxis.setAxisLineStroke(new BasicStroke(1.5f)); // 坐標軸粗細
265 vaxis.setAxisLinePaint(new Color(215, 215, 215)); // 坐標軸顏色
266 vaxis.setLabelPaint(new Color(10, 10, 10)); // 坐標軸標題顏色
267 vaxis.setTickLabelPaint(new Color(102, 102, 102)); // 坐標軸標尺值顏色
268 vaxis.setLowerMargin(0.06d);// 分類軸下(左)邊距
269 vaxis.setUpperMargin(0.14d);// 分類軸下(右)邊距,防止最后邊的一個數據靠近了坐標軸。
270 plot.setNoDataMessage("找不到可用數據
");//沒有數據時顯示的文字說明。
271 XYLineAndShapeRenderer xylineandshaperenderer = (XYLineAndShapeRenderer)plot.getRenderer();
272 //第一條折線的顏色
273 xylineandshaperenderer.setBaseItemLabelsVisible(true);
274 xylineandshaperenderer.setSeriesFillPaint(0, new Color(127, 128, 0));
275 xylineandshaperenderer.setSeriesPaint(0, new Color(127, 128, 0));
276 xylineandshaperenderer.setSeriesShapesVisible(0, true);
277 xylineandshaperenderer.setSeriesShapesVisible(1, true);
278 xylineandshaperenderer.setSeriesShapesVisible(2, true);
279 xylineandshaperenderer.setSeriesShapesVisible(3, true);
280 xylineandshaperenderer.setSeriesShapesVisible(4, true);
281 //折線的粗細調
282 StandardXYToolTipGenerator xytool = new StandardXYToolTipGenerator();
283 xylineandshaperenderer.setToolTipGenerator(xytool);
284 xylineandshaperenderer.setStroke(new BasicStroke(1.5f));
285 // 顯示節點的值
286 xylineandshaperenderer.setBaseItemLabelsVisible(true);
287 xylineandshaperenderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(
288 ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_CENTER));
289 xylineandshaperenderer.setBaseItemLabelGenerator(new StandardXYItemLabelGenerator());
290 xylineandshaperenderer.setBaseItemLabelPaint(new Color(102, 102, 102));// 顯示折點數值字體的顏色
291
292 ValueAxis rangeAxis = plot.getRangeAxis();
293 //設置最高的一個Item與圖片頂端的距離
294 rangeAxis.setUpperMargin(0.2);
295 //設置最低的一個Item與圖片底端的距離
296 rangeAxis.setLowerMargin(0.3);
297 //在圖表中加區域加區域
298 if(isAreaText){
299 lowpress = 62;
300 uperpress = 400;
301 IntervalMarker intermarker = new IntervalMarker(lowpress, uperpress);
302 intermarker.setPaint(Color.decode("#66FFCC"));// 域顏色
303 intermarker.setLabelFont(new Font("SansSerif", 41, 14));
304 intermarker.setLabelPaint(Color.RED);
305 intermarker.setLabel(areaText);
306 if (dataset != null) {
307 plot.addRangeMarker(intermarker, Layer.BACKGROUND);
308 }
309 }
310 return chart;
311 }
312
313
314 /**
315 *<br> 方法名稱:getGraphURL
316 *<br> 功能描述:取得session中圖像的地址;
317 *<br> 返 回 值:String
318 *<br> 創 建 人:
319 *<br> 創建日期:Mar 30, 2010 1:09:51 PM
320 */
321 public static String getGraphURL(JFreeChart chart, HttpSession session,
322 HttpServletRequest request, int width, int height)throws IOException {
323 String filename = ServletUtilities.saveChartAsPNG(chart, width, height,null, session);
324 String graphURL = request.getContextPath()+ "/servlet/DisplayChart?filename=" + filename;
325 return graphURL;
326 }
327
328 }
329
330
2、模擬數據
1 //柱狀圖
2 DefaultCategoryDataset dataset = new DefaultCategoryDataset();
3 dataset.setValue(5003, "北京", "Corejava");
4 dataset.setValue(3333, "上海", "Corejava");
5 dataset.setValue(5343, "廣州", "Corejava");
6 dataset.setValue(2000, "貴州", "Corejava");
7
8 dataset.setValue(1000, "北京", "JavaWeb");
9 dataset.setValue(6300, "上海", "JavaWeb");
10 dataset.setValue(4000, "廣州", "JavaWeb");
11
12 dataset.setValue(2000, "北京", "jquery");
13 dataset.setValue(1000, "上海", "jquery");
14 dataset.setValue(1000, "廣州", "jquery");
15 JFreeChart jfreechart = JFreeChartCreater.createBarChart(dataset, "課件使用情況條形圖", "課件制作者", "可見使用次數", true);
16
17 //折線圖
18 // 創建第一條時序線
19 TimeSeries pop1 = new TimeSeries("流行趨勢1", Day.class);
20 pop1.add(new Day(10, 1, 2004), 100);
21 pop1.add(new Day(10, 2, 2004), 150);
22 pop1.add(new Day(10, 3, 2004), 250);
23 pop1.add(new Day(10, 4, 2004), 275);
24 pop1.add(new Day(10, 5, 2004), 325);
25 pop1.add(new Day(10, 6, 2004), 425);
26 // 創建第二條時序線
27 TimeSeries pop2 = new TimeSeries("流行趨勢2", Day.class);
28 pop2.add(new Day(20, 1, 2004), 200);
29 pop2.add(new Day(20, 2, 2004), 250);
30 pop2.add(new Day(20, 3, 2004), 450);
31 pop2.add(new Day(20, 4, 2004), 475);
32 pop2.add(new Day(20, 5, 2004), 125);
33 pop2.add(new Day(20, 6, 2004), 150);
34 JFreeChart jfreechart = JFreeChartCreater.JFreeChartSeriesChart("課件使用情況條形圖", null, "X軸", "Y軸", dataset,false,null,0,0);
35
36 //餅圖
37 DefaultPieDataset dataset = new DefaultPieDataset();
38
39 dataset.setValue("java程序設計語言", 10000);
40 dataset.setValue("JSP基礎與案例開發詳解", 20000);
41 dataset.setValue("struts基礎與案例開發詳解", 30000);
42 dataset.setValue("精通JSF", 4000);
43 JFreeChart jfreechart = JFreeChartCreater.createPieChart(dataset,
44 "課件使用情況條形圖", false);
45
46 request.setAttribute("jfreechart", jfreechart);
3、jsp頁面
1 <%@ page language="java" pageEncoding="utf-8"%>
2 <%@ include file="/includes/taglibs.jsp"%>
3 <jsp:directive.page import="org.jfree.chart.*"/>
4 <jsp:directive.page import="org.jfree.chart.entity.*"/>
5 <jsp:directive.page import="org.jfree.chart.servlet.ServletUtilities"/>
6 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
7 <html xmlns="http://www.w3.org/1999/xhtml">
8 <head>
9 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
10 <title>課件使用情況柱狀圖</title>
11 </head>
12 <body>
13 <%
14 JFreeChart jfreechart = (JFreeChart) request.getAttribute("jfreechart");
15 StandardEntityCollection sec = new StandardEntityCollection();
16 ChartRenderingInfo info = new ChartRenderingInfo(sec);
17 String filename = ServletUtilities.saveChartAsJPEG(jfreechart, 500,300, info, session);
18 String graphURL = request.getContextPath()+ "/servlet/DisplayChart?filename=" + filename;
19 %>
20
21 <P ALIGN="CENTER">
22 <img src="<%=graphURL%>" width=500 height=300 border=0 usemap="#map0">
23 </P>
24 <p ALIGN="CENTER">
25 <input type="button" value="關閉" onclick="JavaScript:window.close()"/>
26 </p>
27 </body>
28 </html>
29