Chart a new course with JFreeChart(JFreeChart
Tutorial)
As a developer, I am often asked to demonstrate new applications. After
doing many demos, I noticed that users are often initially more interested in
what an application looks like than what it does. I have also noticed that one
of the best ways to make a good first impression is with a colorful, three-
dimensional chart.
JFreeChart is a popular open source Java charting library that can generate
most common chart types, including pie, bar, line, and Gantt charts. In
addition, the JFreeChart API supports many interactive features, such as tool
tips and zooming. JFreeChart provides an excellent choice for developers
who need to add charts to Swing- or web-based applications.
Note: The following examples are based on JFreeChart version 0.9.4. To
compile and run the code included with this column, you must have two jar
files from the JFreeChart distribution, jfreechart-0.9.4.jar and jcommon-
0.7.1.jar, in your classpath.
Charts and datasets
To create a chart using JFreeChart, you must create a Dataset, which you
then use to create a JFreeChart. A Dataset contains the data that displays in
the chart. JFreeChart features many different Dataset objects, which you can
use to create assorted types of charts. Once you create a Dataset, you next
create the actual chart. JFreeChart uses an object appropriately named
JFreeChart to represent charts. You create JFreeChart objects from Dataset
objects with the ChartFactory class. In the following examples, we will create
pie, XY, and bar charts along with their corresponding Dataset objects.
Pie chart
A pie chart is created from a PieDataset. The following example creates a
PieDataset using the DefaultPieDataset class, adds two values via the
setValue() method, and then creates a pie chart with the ChartFactory's
createPieChart() method. This example will create a pie chart with the title
"Sample Pie Chart," a legend, and two slices: JavaWorld with 75 percent of
the pie, and Other with the other 25 percent:
DefaultPieDataset pieDataset = new DefaultPieDataset();
pieDataset.setValue("JavaWorld", new Integer(75));
pieDataset.setValue("Other", new Integer(25));