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

时间:2009-03-20 07:12:29

标签: java jfreechart linegraph

HI全部:
   我使用下面的图表来显示线图。当我运行以下代码时,我正在获取窗口,但它是空白的,不显示图形。请帮助我,并告诉我如何使用下面的代码在html页面中显示线图。

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);
    }
}

2 个答案:

答案 0 :(得分:5)

我之前也做过这个,但我也有代码,所以这里有线索..

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

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作为其他页面中的图像源,例如像这样..

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

你已经完成了:)

答案 1 :(得分:0)

您使用的摇摆方法在网络设置中无效。您必须生成一个图像,并将其展平为例如一个JPEG字节流,并返回THAT作为来自servlet的具有正确MIME类型的响应。

我之前做过很多次,但是没有代码了。

相关问题