How to display line graph using JFreeChart in jsp?

两盒软妹~` 提交于 2019-11-28 06:02:16

问题


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

回答1:


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

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

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" ..>

And you're done :)




回答2:


You are using a swing approach which does not work in a web setting. You must generate an Image, and flatten it to e.g. a JPEG byte stream, and return THAT as a response from your servlet with a correct MIME type.

I did this many moons ago but do not have the code anymore.



来源:https://stackoverflow.com/questions/665222/how-to-display-line-graph-using-jfreechart-in-jsp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!