如何在JSP中使用JFreeChart显示折线图?

问题描述:

大家好:
我正在使用以下显示折线图.当我运行下面的代码时,我正在获取窗口,但它为空白并且不显示图形.请帮助我,并告诉我如何使用以下代码在html页面中显示折线图.

HI All:
I am using the below to diplay the line graph. when i run the below code, i am getting the window but it is blank and not displaying the graph. Please help me and also tell me how to diplay the line graph in html page using below code.

import org.jfree.chart.*;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.xy.*;

public class xyLine {

    public static void main(String arg[]) {
        XYSeries series = new XYSeries("Average Weight");
        series.add(20.0, 20.0);
        series.add(40.0, 25.0);
        series.add(55.0, 50.0);
        series.add(70.0, 65.0);
        XYDataset xyDataset = new XYSeriesCollection(series);
        JFreeChart chart = ChartFactory.createXYLineChart(
            "XYLine Chart using JFreeChart", "Age", "Weight",
            xyDataset, PlotOrientation.VERTICAL, true, true, false);
        ChartFrame frame1 = new ChartFrame("XYLine Chart", chart);
        frame1.setVisible(true);
        frame1.setSize(300, 300);
    }
}

我也有一段时间做过,但是我也有代码,所以这里是线索.

I did this some time ago as well, but I also have the code, so here's the clue..

正如ThorbjørnRavn Andersen所说,您必须拥有一个生成图像而不是网页的servlet.这意味着您的servlet的processRequest方法看起来像这样:

As Thorbjørn Ravn Andersen said you have to have a servlet generating images instead of web pages. That means that your servlet's processRequest method looks something like this:

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

        response.setContentType("image/png");
        ServletOutputStream os = response.getOutputStream();
        ImageIO.write(getChart(request), "png", os);
        os.close();
    }

private RenderedImage getChart(HttpServletRequest request) {
        String chart = request.getParameter("chart");
        // also you can process other parameters like width or height here
        if (chart.equals("myDesiredChart1")) {
            JFreeChart chart = [create your chart here];
            return chart.createBufferedImage(width, height)
        }

然后,您可以将此servlet用作其他页面中的图像源,例如.

Then you can use this servlet as a source of image in other pages for example like this..

<img src="/ChartDrawerServlet?chart=myDesiredChart1&width=..and other processed parameters" ..>

您已经完成了:)