|
JFreeChart is an open source charting library implemented in Java. It provides
the capability to dynamically create sophisticated charts and incorporate them into Java
applications. The library supports a variety of chart types, including pie, bar, line, area
and other types of charts. It also provides support for more complex charts, such as Gantt
charts, candlestick charts, stacked charts and polar charts.
In this article, I'll cover the basic steps involved in creating
charts using the JFreeChart library, with an emphasis on how to incorporate them into web sites.
Simply creating a chart image using the library is not enough. My goal is to show how charts can
be produced as an integral part of a web page, emdedded directly within the page content area
and surrounded by all the normal aspects of a functional web site, such as menus, banners, etc.
A simple pie chart generated by JFreeChart is shown below:
To accomplish the goal of embedding charts into a web page, we're
going to take a two-step approach. First, we'll concentrate on implementing a Java servlet that can
generate a chart image using JFreeChart. Second, we'll show how that image can be incorporated into a
web page. If you're unfamiliar with creating servlets, you can review my previous article on
Java Servlets.
A Charting Servlet
Servlets are created by extending the javax.servlet.HttpServlet class, and
providing an implementation for the appropriate methods. As shown in Listing 1, this servlet
implements the doGet method, which in turn calls the doTestPieChart method.
Listing 1: ChartServlet Source Code
package keenertech.metrics.servlets;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.*;
import javax.servlet.http.*;
import java.awt.Color;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.DefaultPieDataset;
public class ChartServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
doTestPieChart(request, response);
} // End Method
/**
* This method creates a test pie chart using internally
* generated data. This method can be used to test the
* basic JFreeChart setup and the basic servlet
* configuration.
*
* @param request The HttpServletRequest request,
* which contains lots of useful
* information about the request.
*
* @param response The HttpServletResponse object,
* which allows the output being sent
* back to be tailored.
*/
protected void doTestPieChart(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
OutputStream out = response.getOutputStream();
try
{
DefaultPieDataset dataset = new DefaultPieDataset();
dataset.setValue("Graphic Novels", 192);
dataset.setValue("History", 125);
dataset.setValue("Military Fiction", 236);
dataset.setValue("Mystery", 547);
dataset.setValue("Performing Arts", 210);
dataset.setValue("Science, Non-Fiction", 70);
dataset.setValue("Science Fiction", 989);
JFreeChart chart = ChartFactory.createPieChart(
"Books by Type", // Title
dataset, // Data
true, // Yes, display the legend
false, // No, don't display tooltips
false // No, no URLs
);
chart.setBackgroundPaint(Color.white);
response.setContentType("image/png");
ChartUtilities.writeChartAsPNG(out, chart, 400, 300);
}
catch (Exception e)
{
System.out.println(e.toString());
}
finally
{
out.close();
}
} // End Method
} // End Class
|
The bulk of the work is done in the doTestPieChart method.
I've set it up this way so that, theoretically, this servlet could be set up in the
future to generate different types of charts based on incoming arguments. Each type
of chart could be generated by a separate method.
Creating a chart with JFreeChart follows a simple sequence of steps:
Create a Dataset object containing the data that's required for
the chart. JFreeChart conveniently supports a variety of Dataset classes to
support the different types of charts.
Call the appropriate method in the ChartFactory class
to generate the desired type of chart, passing in the Dataset and any required
arguments. This call will generate an instance of the JFreeChart class,
which is essentially a representation of your chart.
Call various methods of the JFreeChart class as needed to
customize the chart.
Output the chart in some useful fashion, possibly by saving an image
to a file or sending the image to a browser via an output stream.
In Listing 1, a DefaultPieDataset object is created and then
populated with data. The DefaultPieDataset object is passed as an argument to the
createPieChart method of the ChartFactory class.
Then some customization needs to be done. By default, the chart will have a
gray background (which is ugly, trust me). So, the setBackgroundPaint method is called
to set the background to white. As you might expect, there are also numerous other methods that
can be used to customize other aspects of the chart.
But where is "Color.white" defined? In this instance, JFreeChart is taking
advantage of colors that have already been defined in java.awt.Color. AWT stands for
the Abstract Window Toolkit, which is a library of user interface components and utilities
that's been around for over a decade. Except for its convenient color definitions for some of
the more commonly used colors, AWT isn't otherwise pertinent for generating charts targeted
for web pages.
The code below retrieves a reference to the output stream of the response
object. We can use that output stream to send an image back to the browser.
OutputStream out = response.getOutputStream();
Now comes the tricky part. We've generated the chart object, but we need to
create an image of the chart and send it back as part of the response. First, the
setContentType method is used to inform the browser that we're sending back an image,
not an HTML file. Next, we use the writeChartAsPNG method from the ChartUtilities
class to write a PNG image of the chart to the output stream of the response, specifying a
width of 400 and a height of 300.
response.setContentType("image/png");
ChartUtilities.writeChartAsPNG(out, chart, 400, 300);
When deployed, this servlet can be accessed using a URL like:
http://www.yourwebsite.com/servlet/ChartServlet
The servlet will generate the JFreeChart chart displayed earlier in this
article. But it doesn't embed the chart image into the content of a full-featured web page.
That will be the next step.
Embedding a Chart
It turns out that embedding a JFreeChart chart within a web page
is almost absurdly easy, as shown in Listing 2. To embed a chart, use a
regular HTML "img" tag, with the "src" attribute of the tag set to the URL of
the charting servlet.
Listing 2: HTML Page With Embedded Chart
<html>
<head>
<title>Test Chart</title>
</head>
<body>
<div align=center>
<img src=“/servlet/ChartServlet” width=400 height=300 border=0>
</div>
</body>
</html>
|
The charting servlet will generate the chart, sending the
image of the chart back to the user's browser. The chart will typically
appear a second or so after the rest of the web page appears.
Simple. In fact, look closely at the code in Listing
2. That's straight HTML. Your web page doesn't have to be in any
particular language in order to make use of an embedded chart; it just
has to have access to the charting servlet.
This can be useful in creating hybrid solutions. A
client may have a vital web site implemented in PHP, but that PHP site
can still use charts created by a Java-based servlet as long as
the servlet is accessible to the site.
This also points out a potential security issue.
Anybody that can reference the servlet can generate a chart. It may
be desirable to place a security check on such requests before
generating a chart and sending it back to the requester. This is
easy to do, since the servlet has full access to the request object.
A Multi-Chart Servlet
It would be painful, though feasible, to create
a different servlet for every chart that we wanted to implement.
Listing 3 shows a revised version of the doGet method
that I've used to create a servlet that can generate multiple types of
charts depending on the needs of the user.
Listing 3: The Revised doGet Method
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
String strChartType = request.getParameter("type");
if (strChartType != null)
{
if (strChartType.equals("Test1"))
{
doTestPieChart(request, response);
}
if (strChartType.equals("Test2"))
{
doTestBarChart(request, response);
}
}
} // End Method
|
Now you can see why I separated the generation of
my original pie chart into a separate method. In the code above,
the doGet method checks the "type" parameter to determine what
type of chart to generate. In this solution, it is expected that
the "type" parameter would be passed as a URL parameter.
Also, in real life, you'd probably want to add some error handling
to this solution, perhaps passing back a graphic that says "Unknown
Chart Type" if a bad chart type was provided.
Conclusion
The JFreeChart library provides an effective way to create
sophisticated and eye-catching charts dynamically. While I've illustrated
how JFreeChart can be used to embed graphics into web sites, it should be
equally obvious that JFreeChart can also be used effectively in applets and
Java applications.
JFreeChart is a highly functional, mature, and flexible
technology that can be easily incorporated into real-world applications.
Even better, as an open source technology, you can "take it with you"
wherever you go.
References
There are a number of relevant references available online
concerning JFreeChart:
JFreeChart Home Page
http://www.jfree.org/jfreechart
The Home page for the JFreeChart application; the web site is managed by
JFreeChart's original creator, David Gilbert.
Generated API Documentation
http://www.jfree.org/jfreechart/api/gjdoc/index.html
Documentation for the JFreeChart API, generated directly from the
comments contained in the source files. This is invaluable if you're
doing any serious customization of charts.
Visualize Your Oracle Database Data with JFreeChart
http://www.oracle.com/technology/pub/articles/marx-jchart.html
A great article, released Sept 2007, that illustrates the creation of several
different types of charts using JFreeChart. Also discusses producing charts using
database queries, XML, etc.
|