A quick how to use JFreeChart quide can be found at- https://robbamforth.wordpress.com/2008/10/30/java-jfreechart-graphs-and-charts-in-java/
I wanted to be able to output the the charts to a picture file (JPEG) programatically. After a bit of research I got the following methods to paint the chart and output the image to a file.
Add these 2 methods to the class that creates the charts:
Method 1 saveToFile():
public static void saveToFile(JFreeChart chart,
String aFileName,
int width,
int height,
double quality)
throws FileNotFoundException, IOException
{
BufferedImage img = draw( chart, width, height );
FileOutputStream fos = new FileOutputStream(aFileName);
JPEGImageEncoder encoder2 =
JPEGCodec.createJPEGEncoder(fos);
JPEGEncodeParam param2 =
encoder2.getDefaultJPEGEncodeParam(img);
param2.setQuality((float) quality, true);
encoder2.encode(img,param2);
fos.close();
}
Method 2 draw():
protected static BufferedImage draw(JFreeChart chart, int width, int height)
{
BufferedImage img =
new BufferedImage(width , height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = img.createGraphics();
chart.draw(g2, new Rectangle2D.Double(0, 0, width, height));
g2.dispose();
return img;
}
Call the saveToFile method to save the chart to a JPEG:
try{
saveToFile(pieChart,”c:/test.jpg”,500,300,100);
}catch(Exception e){
e.printStackTrace();
}
This tells the application to save the current pieChart to a file called c:/test.jpg, with a width of 500 a height of 300 and a quality of 100.
The createPiePanel() method will now look like:
public static JPanel createPiePanel(int ring, int call, int off, String title) {
JFreeChart pieChart = createPieChart(createPieDataset(ring, call, off), title);
try{
saveToFile(pieChart,”c:/test.jpg”,500,300,100);
}catch(Exception e){
e.printStackTrace();
}
return new ChartPanel(pieChart);
}