servlet代碼:
// 創建餅圖數據集
DefaultPieDataset dataset = new DefaultPieDataset();
dataset.setValue("蘋果", 43.2);
dataset.setValue("李子", 27.9);
dataset.setValue("桃", 79.5);
dataset.setValue("哈密瓜", null);
// 通過片區的關鍵值進行升序/降序排序。
dataset.sortByKeys(SortOrder.ASCENDING);
//dataset.sortByKeys(SortOrder.DESCENDING);
// 創建圖表對象
JFreeChart chart = ChartFactory.createPieChart(
"水果銷售圖",
dataset,
true, // 是否生成圖例
true, // 是否生成工具
false // 是否生成URL
);
// 設置標題文字,防止中文亂碼
chart.getTitle().setFont(new Font("黑體",Font.BOLD,18));
PiePlot plot = (PiePlot) chart.getPlot();
// 可以自行控制餅形圖某個片區的顏色
plot.setSectionPaint("Category 1", new Color(200, 255, 255));
// 餅圖外形默認一條細黑線勾畫出來,設置去掉
plot.setSectionOutlinesVisible(false);
// 設置標籤的顯示格式
plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0}({2} percent)"));
// 設置標籤的背景顏色
plot.setLabelBackgroundPaint(new Color(220, 220, 220));
// 設置標籤的字體
plot.setLabelFont(new Font("黑體",Font.BOLD,10));
// 設置忽略0值,默認忽略
plot.setIgnoreZeroValues(true);
// 忽略NULL值
plot.setIgnoreNullValues(true);
// 取出某個片區突出顯示,0.3(30 persent)代碼偏離的值是半徑的長度×0.3.代碼如下
//plot.setExplodePercent("Category 1", 0.3);
// 設置標籤的字體
//plot.setLabelFont(new Font("Arial Black", 0, 20));
// 設置無數據時信息提示
plot.setNoDataMessage("沒有有效的數據顯示!");
plot.setNoDataMessageFont(new Font("黑體", 2, 20));
plot.setNoDataMessagePaint(Color.red);
String filename = ServletUtilities.saveChartAsPNG(chart, 600, 400, null,request.getSession());
System.out.println(filename);
String graphURL = request.getContextPath()+"/displaychart?filename="+filename;
request.setAttribute("graphURL", graphURL);
request.getRequestDispatcher("/bar/index.jsp").forward(request, response);
jsp:
<img src="${graphURL }">