Monday, December 2, 2013

How To Use JFreeChart In Java

Do you want to visualize your data from your database in Java? Well some guy started to develop a FREE and very good chart library in Java. The good thing about this is that is it free and open source, so anytime you want to change something you want to meet your needs is just like a piece of cake.

First, you have to download the library itself JFreeChart download note it is being hosted on SourceForge.
If you're using Eclipse IDE this my post might come in handy to adding library to your classpath.

Create a new project and new class then copy/paste this code which I will be explaining later:


import javax.swing.JFrame;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PiePlot3D;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;
import org.jfree.util.Rotation;


public class HelloChart extends JFrame {
 
 private static final long serialVersionUID = 1L;

 public HelloChart(String applicationTitle, String chartTitle) {
        super(applicationTitle);
        PieDataset dataset = createDataset();
        JFreeChart chart = createChart(dataset, chartTitle);
        ChartPanel chartPanel = new ChartPanel(chart);
        chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
        setContentPane(chartPanel);

    }
    
    private  PieDataset createDataset() {
        DefaultPieDataset result = new DefaultPieDataset();
        result.setValue("McDonalds", 40);
        result.setValue("Jolibee", 11);
        result.setValue("Subway", 9);
        return result;
        
    }

    private JFreeChart createChart(PieDataset dataset, String title) {
        JFreeChart chart = ChartFactory.createPieChart3D(title, dataset, true, true, false);
        PiePlot3D plot = (PiePlot3D) chart.getPlot();
        plot.setStartAngle(290);
        plot.setDirection(Rotation.CLOCKWISE);
        plot.setForegroundAlpha(0.5f);
        return chart;
    }
    public static void main(String args){
     HelloChart demo = new HelloChart("Comparison", "Which fast food are the best?");
        demo.pack();
        demo.setVisible(true);
 }
   
} 

Basically, what we need to render our chart is to make a dataset. In this example, we want created a DefaultPieDataSet and add some values in it. Then we make an instance of JFreeChart and customize it along with the dataset we have just created. Finally, we give it to our JFrame's  content pane for the user to see it. Here are one of the examples when you downloaded the library with demo file.

Try to explore the whole demo application and get helped in its forum and some tutorials. Thank you for reading my post!

No comments:

Post a Comment