JAVA – JFreeChart – How To Save a JFreeChart to JPEG File

 

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

    }

Advertisements

JAVA – JFreeChart – graphs and charts in JAVA

 

I came across a fantastic tool this week for creating graphs and charts in JAVA – JFreeChart.

The JARs and API can be downloaded from the following link:
http://www.jfree.org/jfreechart/download.html

 

STEP 1:
Once downloaded, the first step is to unzip the content and look for 2 files called –
jcommon-1.0.14.jar and jfreechart-1.0.11.jar
The file names may change slightly with new releases.
Copy these 2 files into the working directory of your JAVA application – adding then to the class path. 

 
 

 

If using Netbeans, copy jcommon-1.0.14.jar andjfreechart-1.0.11.jar to the project folder in windows explorer.
In Netbeans – right-click the project in the projects window and select properties.
Select the Libraries category.
On the Compile tab click Add JAR/Folder.
Select jcommon-1.0.14.jar andjfreechart-1.0.11.jar  and click open.
Click OK.
jcommon-1.0.14.jar andjfreechart-1.0.11.jar are now in the class path of the current JAVA application.

 

STEP 2 Creating a pie chart in a swing application:

I have found that jScrollPane is a use full object to hold the chart. When building your Jframe add an empty JScrollPane somewhere on your window that will hold the chart.

The following example assumes that the JFrame is already created and Pack() has been called.

Add the following 3 methods into the GUI class:

   // CREATE THE PIE CHART
   public static JPanel createPiePanel() {

        JFreeChart pieChart = createPieChart(createPieDataset());

        return new ChartPanel(pieChart);

    }

   
    // BUILD THE PIE CHART

    private static JFreeChart createPieChart(PieDataset dataset) {

 

        JFreeChart chart = ChartFactory.createPieChart(

            “Chart Title”,  // chart title

            dataset,             // data

            true,               // include legend

            true,

            false

        );

 

        PiePlot plot = (PiePlot) chart.getPlot();

        plot.setSectionOutlinesVisible(false);

        plot.setNoDataMessage(“No data available”);

 

        return chart;

 

    }

   

    // CREATE THE PIE CHART DATA

    private static PieDataset createPieDataset() {

        DefaultPieDataset dataset = new DefaultPieDataset();

       

        dataset.setValue(“One”, new Double(43.2));

        dataset.setValue(“Two”, new Double(10.0));

        dataset.setValue(“Three”, new Double(27.5));

        dataset.setValue(“Four”, new Double(17.5));

        dataset.setValue(“Five”, new Double(11.0));

        dataset.setValue(“Six”, new Double(19.4));

 

         return dataset;

    }

 

 

 

 

 

STEP 3: Add the created pie chart into an already existing JScrollPane:

Assuming the there is a valid JScrollPane in the main GUI of the Swing application, use the following code to add the chart to it.

// REMOVE ANY ITEM CURRENTLY IN THE JCROLLPANE
JScrollPane.getViewport().removeAll();


// BUILD AND ADD THE CHART TO THE JSCROLLPANE

JScrollPane.getViewport().add(createPiePanel());

When this is teamed with a JDBC (https://robbamforth.wordpress.com/2008/10/28/java-sql-server-2005-odbc-jdbc-connection/) you can build up graphs based on SQL data.

 

You can learn how wo export the chart to a JPEG feil here: https://robbamforth.wordpress.com/2008/11/05/java-jfreechart-how-to-save-a-jcfreechart-to-jpeg-file/