日期:2014-05-18  浏览次数:20618 次

如何显示jfreechart时序图
从网上找了一个用jfreechart作时序图的例子,但是这个例子是把生成的图片保存在硬盘上,而不是显示出来。代码如下,请问是否能帮我让图片显示在web页面上,谢谢!

<%@ page language="java" contentType="text/html; charset=GBK" pageEncoding="GBK" import="java.util.Date,java.text.SimpleDateFormat,java.util.Enumeration" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<%@page import="DBConnection.JdbcPool"%>
<%@include file="../../css/Content.css" %>
<%@include file="../../JS/autoset.js" %>

<%@ page import="java.awt.Font"%>
<%@ page import="javax.swing.JPanel"%>
<%@ page import="java.text.SimpleDateFormat"%>
<%@ page import="org.jfree.chart.ChartFactory"%>
<%@ page import="org.jfree.chart.ChartFrame"%>
<%@ page import="org.jfree.chart.ChartUtilities"%>
<%@ page import="org.jfree.chart.JFreeChart"%>
<%@ page import="org.jfree.chart.axis.DateAxis"%> 
<%@ page import="org.jfree.chart.plot.XYPlot"%> 
<%@ page import="org.jfree.data.time.Day"%>
<%@ page import="org.jfree.data.time.TimeSeriesCollection"%>

<%@ page import="org.jfree.chart.ChartPanel"%> 
<%@ page import="org.jfree.chart.axis.ValueAxis"%> 
<%@ page import="org.jfree.data.time.*"%>

<%@ page import="org.jfree.data.xy.XYDataset"%> 
<%@ page import="org.jfree.ui.ApplicationFrame"%> 
<%@ page import="org.jfree.ui.RefineryUtilities"%>

<%@ page import="java.io.*"%>
<%@ page import="java.sql.*"%>

<%
 // 创建第一条时序线
  TimeSeries pop1 = new TimeSeries("Population1", Day.class);
  pop1.add(new Day(10, 1, 2004), 100);
  pop1.add(new Day(10, 2, 2004), 150);
  pop1.add(new Day(10, 3, 2004), 250);
  pop1.add(new Day(10, 4, 2004), 275);
  pop1.add(new Day(10, 5, 2004), 325);
  pop1.add(new Day(10, 6, 2004), 425);
  
  // 创建第二条时序线
  TimeSeries pop2 = new TimeSeries("Population2", Day.class);
  pop2.add(new Day(20, 1, 2004), 200);
  pop2.add(new Day(20, 2, 2004), 250);
  pop2.add(new Day(20, 3, 2004), 450);
  pop2.add(new Day(20, 4, 2004), 475);
  pop2.add(new Day(20, 5, 2004), 125);
  pop2.add(new Day(20, 6, 2004), 150);
   
  // 创建一个时序集合
  TimeSeriesCollection dataset = new TimeSeriesCollection();
  dataset.addSeries(pop1);
  dataset.addSeries(pop2);
  
  // 产生时序图 
  JFreeChart chart = ChartFactory.createTimeSeriesChart("人口统计时序 图","Date","Population",dataset,true,true,false);
  
  ChartFrame cf = new ChartFrame("时序图",chart);
  cf.pack();
  cf.setSize(500,300);
  cf.setVisible(true);

//保存图片,请问如何实时显示出来
ChartUtilities.saveChartAsJPEG(new File("C:\\TimeSeriesChart1.jpg"), chart, 500, 300);
%>

------解决方案--------------------
为了将生成的图表直接传给客户端浏览器,只需要将例子中的文件流换成是通过HttpServletResponse对象获取到的输出流,
自己写个Servlet,
如:
Java code

public class ChartDemoServlet extends HttpServlet {
    public void service(ServletRequest req, ServletResponse res)
        throws ServletExce