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 }">