WebChart.java package net.sentom.chart; import java.awt.Insets; import java.awt.Font; import java.io.PrintWriter; import javax.servlet.http.HttpSession; import org.jfree.data.*; import org.jfree.chart.*; import org.jfree.chart.plot.*; import org.jfree.chart.entity.*; import org.jfree.chart.urls.*; import org.jfree.chart.servlet.*; import org.jfree.chart.labels.StandardPieToolTipGenerator; /** * @author sentom * * To change the template for this generated type comment go to * Window>Preferences>Java>Code Generation>Code and Comments */ public class WebChart { private DefaultPieDataset data = new DefaultPieDataset(); public void setValue(String key,double value){ data.setValue(key,value); } public String generatePieChart(String title, HttpSession session, PrintWriter pw) { String filename = null; try { //建立chart對象 PiePlot plot = new PiePlot(data); plot.setInsets(new Insets(0, 5, 5, 5)); //在統計圖片上建連結 plot.setURLGenerator(new StandardPieURLGenerator("link.jsp","section")); plot.setToolTipGenerator(new StandardPieToolTipGenerator()); JFreeChart chart = new JFreeChart("", JFreeChart.DEFAULT_TITLE_FONT, plot, true); chart.setBackgroundPaint(java.awt.Color.white);//設定圖片的背景色 Font font = new Font("黑體",Font.CENTER_BASELINE,20);//設定圖片標題的字型 和大小 TextTitle _title = new TextTitle(title); _title.setFont(font); chart.setTitle(_title); //把產生的圖片放到臨時目錄 ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection()); //500是圖片長度,300是圖片高度 filename = ServletUtilities.saveChartAsPNG(chart, 500, 300, info, session); ChartUtilities.writeImageMap(pw, filename, info); pw.flush(); } catch (Exception e) { System.out.println("Exception - " + e.toString()); e.printStackTrace(System.out); filename = "public_error_500x300.png"; } return filename; } } JSP檔案 <%@ page contentType="text/html;charset=GBK"%> <%@ page import = "java.io.PrintWriter" %> <%@ page import="net.sentom.chart.WebChart"%> <% WebChart chart = new WebChart(); chart.setValue("六月",500); chart.setValue("七月",580); chart.setValue("八月",828); String filename = chart.generatePieChart("www.111cn.net 網站訪問統計表", session, new PrintWriter(out)); String graphURL = request.getContextPath() + "/servlet/DisplayChart?filename=" + filename; %> <HTML> <HEAD> <TITLE>www.sentom.net</TITLE> </HEAD> <BODY> <P ALIGN="CENTER"> <img src="<%= graphURL %>" width=500 height=300 border=0 usemap="#<%= filename %>"> </P> </BODY> </HTML> |