浅析web图形报表的实现(struts+jfreechat)

Share

  现在的报表形式也越来越多了,但是早期的web开发人员都还是知道jfreechat,毕竟是比较成熟的wp了。今天重新拿出来回顾一下。
  首先,就是设置一个数据源(pie的),这里我们写死在一个类里面。

<br /> &nbsp; &nbsp;DefaultPieDataset dataset = new DefaultPieDataset();<br /> &nbsp; &nbsp;<br /> &nbsp; &nbsp;dataset.setValue("裤子",100);<br /> &nbsp; &nbsp;dataset.setValue("鞋子",200);<br /> &nbsp; &nbsp;dataset.setValue("帽子",300);<br /> &nbsp; &nbsp;dataset.setValue("内衣",20);<br /> &nbsp; &nbsp;dataset.setValue("短裤",120);<br /> &nbsp; &nbsp;dataset.setValue("裙子",315);<br /> &nbsp; &nbsp;<br /> &nbsp; &nbsp;return dataset;<br />

上面就完成了对要生成图片的数据源。

接下来,对一个chat进行初始化设置(我这里是生成的png格式的图片,以便编辑,并且存放在服务器的temp目录):

JFreeChart chart = ChartFactory.createPieChart3D(“饼型图”, // chart title
piedata, // data
true, // include legend
true,
false
);
//设置图片的背景色
chart.setBackgroundPaint(new Color(215,215,215));

//设置透明度,好像对servlet没有用
chart.setBackgroundImageAlpha(0.5f);

//设置图片标题的字体和大小
TextTitle _title = new TextTitle(title);
_title.setFont(titleFont);
chart.setTitle(_title);

PiePlot plot = (PiePlot) chart.getPlot();

plot.setNoDataMessage(“can't find any data,please set one!”);
plot.setNoDataMessagePaint(Color.red);

//指定 section 轮廓线的厚度(OutlinePaint不能为null)
plot.setOutlineStroke(new BasicStroke(0));

//设置第一个 section 的开始位置,默认是12点钟方向
plot.setStartAngle(90);

plot.setToolTipGenerator(new StandardPieItemLabelGenerator(unitSytle,
NumberFormat.getNumberInstance(),
new DecimalFormat(“0.00%”)));

//指定图片的透明度
plot.setForegroundAlpha(0.65f);

//引出标签显示样式
plot.setLabelGenerator(new StandardPieItemLabelGenerator(unitSytle,
NumberFormat.getNumberInstance(),
new DecimalFormat(“0.00%”)));

//图例显示样式
plot.setLegendLabelGenerator(new StandardPieItemLabelGenerator(unitSytle,
NumberFormat.getNumberInstance(),
new DecimalFormat(“0.00%”)));

//把生成的图片放到临时目录
ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());

//设置图片名称前缀
ServletUtilities.setTempFilePrefix(“chart-“);

//500是图片长度,300是图片高度
filename = ServletUtilities.saveChartAsPNG(chart, 600, 350, info, session);
//生成图片
ChartUtilities.writeImageMap(pw, filename, info, false);

然后,就是怎么调用了,本文用的是struts,所以我们在Action类里面做相应的参数设置和调用:

<br /> &nbsp; &nbsp;WebChartDataset dataset = new WebChartDataset();<br /> &nbsp; &nbsp;WebChart chart = new WebChart(); &nbsp; &nbsp;<br /> &nbsp; &nbsp;chart.setValue(dataset.createPieData());<br /> &nbsp; &nbsp;<br /> &nbsp; &nbsp;String filename = chart.generatePieChart3D("月统计比例图", <br /> &nbsp; &nbsp; &nbsp; &nbsp;session, out);<br /> &nbsp; &nbsp;<br /> &nbsp; &nbsp;String graphURL = request.getContextPath() <br /> &nbsp; &nbsp; &nbsp; &nbsp;+ "/servlet/DisplayChart?filename=" + filename;<br /> &nbsp; &nbsp;<br /> &nbsp; &nbsp;request.setAttribute("filename",filename);<br /> &nbsp; &nbsp;request.setAttribute("graphURL",graphURL);<br />

好了,这里就剩在页面的展示了下面一句就搞定

” usemap='#' border=”0″/>
[/java]

效果如下图:

本文提供了eclipse的工程源码下载:
[sfile]http://www.icnote.com/files/jspGraphic.rar[/sfile]