views:

4047

answers:

2

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.
Code :
import org.jfree.chart.;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.xy.
;
import org.jfree.data.*;

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

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.

Thorbjørn Ravn Andersen
+1  A: 

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

Martin Lazar