In Java creating any graph or chart like bar chart or pie chart is very easy. For this we have a very light weight but powerful library called JFreeChart. This is an open source library in Java that allows developer to generate charts/graphs when user wants graphs to be regenerated frequently and dynamically. JfreeChart can be downloaded from http://sourceforge.net/project/showfiles.php?group_id=15494&package_id=12428
For this below code snippet I’ve used version jfreechart-0.9.21.jar
The project consists of one jsp file and one servlet. Inside Jsp file in the tag the path of the servlet is given in the src attribute that invokes the servlet. The servlet is responsible in generating the bar chart based on the data given.
Graphtest.jsp
|
 DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”>  <html:html> <HEAD> <TITLE>TITLE> HEAD>  <BODY> <P>The Generated Chart is:<BR> <BR> P> <IMG src=“GraphGen”> BODY> html:html>  |
Â
|
package com.tctalk.chartgen.servlets;  import java.awt.Color; import java.io.IOException; import java.io.OutputStream;  import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;  import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartUtilities; import org.jfree.chart.JFreeChart; import org.jfree.chart.labels.StandardCategoryToolTipGenerator; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.renderer.category.CategoryItemRenderer; import org.jfree.chart.urls.StandardCategoryURLGenerator; import org.jfree.data.category.DefaultCategoryDataset;   public class GraphGen extends HttpServlet {        public void doGet(HttpServletRequest req,                        HttpServletResponse resp)             throws ServletException, IOException {             genGraph(req, resp);        }        public void doPost(HttpServletRequest req,                          HttpServletResponse resp)             throws ServletException, IOException {             genGraph(req, resp);       }        public void genGraph(HttpServletRequest req,                            HttpServletResponse resp) {       try {            OutputStream out = resp.getOutputStream();            // Create a simple Bar chart            System.out.println(“Setting dataset values”);            DefaultCategoryDataset dataset = new DefaultCategoryDataset();             dataset.setValue(30, “Girls”, “SCIENCE CLASS”);            dataset.setValue(30, “Boys”, “SCIENCE CLASS”);             dataset.setValue(10, “Girls”, “ECONOMICS CLASS”);            dataset.setValue(50, “Boys”, “ECONOMICS CLASS”);             dataset.setValue(5, “Girls”, “LANGUAGE CLASS”);            dataset.setValue(55, “Boys”, “LANGUAGE CLASS”);             JFreeChart chart =            ChartFactory.createBarChart3D(            “Comparison between Girls and Boys in Science, “            + “Economics and Language classes”,            “Students Comparisons”,            “No of Students”,            dataset,            PlotOrientation.VERTICAL,            true,            true,            false);       chart.setBackgroundPaint(Color.white);            // Set the background colour of the chart       chart.getTitle().setPaint(Color.blue);            // Adjust the colour of the title       CategoryPlot plot = chart.getCategoryPlot();            // Get the Plot object for a bar graph           plot.setBackgroundPaint(Color.white);      plot.setRangeGridlinePaint(Color.red);       CategoryItemRenderer renderer = plot.getRenderer();       renderer.setSeriesPaint(0, Color.red);       renderer.setSeriesPaint(1, Color.green);       renderer.setItemURLGenerator(        new StandardCategoryURLGenerator(             “index1.html”,             “series”,             “section”));       renderer.setToolTipGenerator(             new StandardCategoryToolTipGenerator());        resp.setContentType(“image/png”);       ChartUtilities.writeChartAsPNG(out, chart, 625, 500);       } catch (Exception e) {       System.err.println(       “Problem occurred creating chart.” + e.getMessage());             }       }  }  |
 And the output is:

jfreechart bar diagram
Explanation of the Java code-
-
To create a Bar chart we first define an instance of the DefaultCategoryDataset object.
-
The setValue() method of this object is used to set the data and name of the bars to be generated.
-
The Bar chart is generated by using createBarChart3D method of CharFactory. This generates 3D version of the Bar chart based on the data set value passed as arguments.
-
Appearances of the Bar are set by using the various self described methods. And finally the Bar chart is generated using writeChartAsPNG() method.
Related Articles:
- JfreeChart Series-3: How to create a dynamic 3D Pie Chart using JFreeChart library in Java You may refer to the earlier tutorials if you have...
- JfreeChart Series-2: How to create a dynamic Pie Chart using JFreeChart library in Java  In the earlier tutorial I showed you how to create...
- Reading user input in java Sometimes in our stand alone java program we need to...
- Step by step guide to create Singleton design pattern with Java Singleton design pattern is a kind of design pattern which...
- How to create Windows executable EXE from a Java Jar Creating Windows executable EXE file from a Jar file: //...
- Java Comparator example Sometimes we need to sort objects based on certain attributes...
- How to load a properties file in Java This tutorial will explain how to access properties file through Java...
- File upload to BLOB field and display attachment dialog box Sometimes a developer needs to provide the feature in their...
- How to test if a String is palindrome or not in Java? Steps to check if a given string is a Palindrome...
- creating non duplicate array from duplicate array in Java This example helps you to generate a fresh and non...
You can subscribe by e-mail to receive news updates and breaking stories.
Oke, now tell me whats actually dynamic about this chart? Looks pretty static to me.
This is dynamic because you are using Jfreechart library and based on your supplied dataset your java program is creating chart? So isn’t it dynamic?
your absolutely correct, but the chart thats produced here is still static because the dataset given is a static set.
I was comparing it with the dynamic charts examples of jfreecharts and they give actual ‘on the fly’ dynamic options to their charts, using sliders, input fields and chart type choosing.
the example is good though so thumbs up, i just expected a different kind of example.
Same eo me fred, I see this as dynamic as you set the chart parameters on the code, is there any way to create the chart and the data being extracted from the database ?
I have used the above jsp and servlet. With Servlet, i got the barcharts but while i was using jsp it is not showing the barcharts. I have used MyEclipse IDE. I have created the servlet in package name as graph and in jsp i have given but it didn’t work. After that i have used because in xml the url-pattern tag has generated as /servlet/GraphGen. But still it didn’t work. Kindly help me in this problem.Please.
With Warm Regards,
Manikanta Mogalluri.