How to use JFree charts in java?

How to use JFree chart in java?

Add the following jar files in class path:
jcommon-1.0.16.jar, jfreechart-1.0.20.jar


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 PieChartExample extends JFrame {
 
public PieChartExample(String applicationTitle, String chartTitle) {
        super(applicationTitle);
        // This will create the dataset
        PieDataset dataset = createDataset();
        // based on the dataset we create the chart
        JFreeChart chart = createChart(dataset, chartTitle);
        // we put the chart into a panel
        ChartPanel chartPanel = new ChartPanel(chart);
        // default size
        chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
        // add it to our application
        setContentPane(chartPanel);
    }
   
 //Creates a sample dataset
    private  PieDataset createDataset() {
        DefaultPieDataset result = new DefaultPieDataset();
        result.setValue("Hyderabad", 25);
        result.setValue("Chennai", 23);
        result.setValue("Mumbai", 30);
        result.setValue("Banglore", 22);
        return result;
    }
 
//Creates a chart
    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;
       
    }
}



Write the  Main class:

public class MainClass {
      public static void main(String[] args) {
PieChartExample example = new PieChartExample("Comparison", "largest city in population");
        example.pack();
        Example.setVisible(true);
    }

}



Search This Blog

All the rights are reserved to this blog is belongs to me only.. Powered by Blogger.