最近开发时,要对一些东西进行统计时用到了JFreeChart画图,所以稍微研究了一下JFreeChart,下面是画饼图的方法的部分代码:
/**
* 饼图
*/
private JFreeChart getPieChart() {
String sql = "select count(id) num,modulename mname from tongji group by mname";
List list = getList(sql);
//创建DefaultPieDataset数据集
DefaultPieDataset dpd = new DefaultPieDataset();
for (Object obj : list) {
Map<String, Object> map = (Map<String, Object>) obj;
//添加数据
dpd.setValue((String) map.get("mname"), (Number) map.get("num"));
}
//创建绘制3D效果饼形图的JFreeChart实例
JFreeChart chart = ChartFactory.createPieChart3D("图片标题",// 图片标题
dpd, // 绘图数据集
true, // 设定是否显示图例
false, // 设定是否显示图例名称
false); // 设定是否生成链接
//当需要在图片上显示中文时,建议不要使用反锯齿功能,这样能够保证汉字的清晰度
chart.setAntiAlias(true);//是否启用反锯齿功能
chart.setBackgroundPaint(Color.LIGHT_GRAY);//设置背景色
//可以自行定义图表标题的字体、样式、大小和颜色等
TextTitle title = chart.getTitle();
title.setFont(new Font("黑体", Font.BOLD, 20)); //标题字体
title.setPaint(Color.BLACK);//标题字体颜色
title.setBackgroundPaint(Color.WHITE);//标题背景
LegendTitle legend = chart.getLegend();//得到图例对象
legend.setBackgroundPaint(Color.WHITE);//图例背景
legend.setItemFont(new Font("宋体", Font.ITALIC, 12)); // 图例的字体
legend.setPosition(RectangleEdge.BOTTOM);//图例位置
//通过绘图区对象设置饼状图的效果
PiePlot plot = (PiePlot) chart.getPlot();//得到绘图区对象
plot.setLabelFont(new Font("宋体", Font.ITALIC, 12)); // 图片上的文字的字体
plot.setOutlineStroke(new BasicStroke(1));//边框粗细
plot.setOutlinePaint(Color.GRAY);//边框颜色
plot.setCircular(false);//默认为圆形,建议在绘制3D效果图时将其设为False
plot.setStartAngle(90);// 设置第一部分 的开始位置
plot.setDirection(Rotation.ANTICLOCKWISE);//设置绘制方向为逆时针
plot.setForegroundAlpha(0.65f);// 指定图片的透明度
String unitSytle = "{0}={1}({2})"; //样式: A部分=35(15.98%)
plot.setLabelGenerator(new StandardPieSectionLabelGenerator(unitSytle,
NumberFormat.getNumberInstance(), new DecimalFormat("0.00%")));// 引出标签显示样式
plot.setLegendLabelGenerator(new StandardPieSectionLabelGenerator(
unitSytle, NumberFormat.getNumberInstance(), new DecimalFormat("0.00%")));// 图例显示样式
//没有数据时显示的内容
plot.setNoDataMessage("无对应的数据,请重新查询。");
plot.setNoDataMessagePaint(Color.red);
plot.setNoDataMessageFont(new Font("黑体", Font.BOLD, 20));
return chart;
}
有了JFreeChart对象,剩下的工作就非常简单了,如果只是显示一下可以:
JFreeChart chart = getPieChart();
ChartFrame pieFrame = new ChartFrame("统计图", chart);
pieFrame.pack();
pieFrame.setVisible(true);
还可以生成一张本地图片,保存在磁盘上:
try {
File file = new File("D:/tj.png"); //保存的位置
ChartUtilities.saveChartAsPNG(file,chart,800,500);//保存为长为:800,高为500
} catch (IOException e) {
e.printStackTrace();
}