Share on Google+Share on Google+

Create Pie Chart using database values

Advertisement
In this section, you will learn how to create a pie chart by retrieving the values from the database.

Create Pie Chart using database values

Java provides JFreeChart library which helps in creating a number of charts.It provides several classes and methods which enables the programmer to create charts very easily. You have already learned bar charts, line charts in the previous sections. Here we are going to create a pie chart by retrieving the values from the database.

Here is the code:

import java.sql.*;
import java.io.*;
import org.jfree.ui.*;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.data.*;
import org.jfree.data.jdbc.JDBCPieDataset;

public class Chart {
	public static void main(String[] args) throws Exception {

		String query = "SELECT * from chart";
		JDBCPieDataset dataset = new JDBCPieDataset(
				"jdbc:mysql://localhost:3306/test", "com.mysql.jdbc.Driver",
				"root", "root");

		dataset.executeQuery(query);
		JFreeChart chart = ChartFactory.createPieChart("Test", dataset, true,
				true, false);
		ChartPanel chartPanel = new ChartPanel(chart);
		chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
		ApplicationFrame f = new ApplicationFrame("Chart");
		f.setContentPane(chartPanel);
		f.pack();
		f.setVisible(true);

	}
}

Output:

Advertisements

Advertisement

Posted on: June 17, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.