使用JFreeChart小结(一)

使用JFreeChart小结:

对于web应用,应先在web.xml中配置servlet,如下:

	<!-- jfreechart  -->
	<servlet>
		<servlet-name>DisplayChart</servlet-name>
		<servlet-class>org.jfree.chart.servlet.DisplayChart</servlet-class>
   	</servlet>
	<servlet-mapping>
		<servlet-name>DisplayChart</servlet-name>
		<url-pattern>/servlet/DisplayChart</url-pattern>
	</servlet-mapping>

 

在Action中调用,基本步骤:

// 设置输出编码格式
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession();

// 整理数据 ...
...
// 进行画图,返回JFreeChart
JFreeChart chart = //...

//得到图片文件,并将其展现到页面上
String file = pageShowChart(chart, title, session, out);
String graphURL = request.getContextPath() + "/servlet/DisplayChart?filename=" + file;

 

public String pageShowChart(JFreeChart chart, String title, HttpSession session, PrintWriter pw)
{
	String filename = null;

	try
	{
		// 设置图片标题的字体和大小
		TextTitle picTitle = new TextTitle(title);
		Font titleFont = new Font("Dialog", Font.PLAIN, 16);
		picTitle.setFont(titleFont);
		chart.setTitle(picTitle);

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

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

		// 825是图片长度,400是图片高度
		filename = ServletUtilities.saveChartAsPNG(chart, 825, 400, info, session);

		ChartUtilities.writeImageMap(pw, filename, info, false);
	}
	catch (Exception e)
	{
		e.printStackTrace();
	}
	return filename;
}

 

在JSP页面显示:

<table id="table1" width="100%" border="0" cellpadding="0" cellspacing="1" class="tb_datalist">
	<tr>
		<td colspan="2" >
			<div align="center">
				<img src="${graphURL }" usemap="${file }" border="0" width="825" height="400" />
			</div>
		</td>
	</tr>
</table>

 

 

关键就在画图,返回JFreeChart了
JFreeChart chart = //...

 

需要使用的包:

jcommon-1.0.0.jar

jfreechart-1.0.8a.jar

至于如何画图返回JFreeChart,javaeye已经有很多文章提到,可以参考:http://www.iteye.com/topic/157328

主要包括饼状图、折线图和柱状图(单组、多组、堆积)

 

附件给出测试源码,以及所需要的包

你可能感兴趣的:(Web,jsp,xml,servlet,jfreechart)