JFreechart Java JDBC Bar Chart Example

In this tutorial, we will explain how to create a bar chart in Java over a JDBC connection using JFreeChart API. The example assumes you have a basic understanding of Java code, if not, don’t worry..we will take you with a step by step approach. Writing this program is not complex ; just that you need to bridge all the required components into a functionally working code. If you break the full code into smaller units, you will find it how easy and simple it is to generate this chart in Java.  We will be using Oracle database for this example.

Here are the steps to create the bar chart:

Download Required JAR files:


Before trying out the example that we are going to provide, make sure you download a copy of the following JAR files:

  • jfreechart-1.0.14.jar
  • ojdbc6.jar
  • jcommon-1.0.17.jar
The example may still work if you don’t have the exact version of the JAR files. If you get any exceptions, post it as a comment and we will have a look.

Prepare Chart Data for JFreechart Example


We run a few queries at this point to create the chart table for us and populate the table with the chart data. You can use your own table or just use the scripts as provided below
/* Create Chart table */
create table chart_Data
(
category varchar2(20),
marks number
)
/* Insert data - Need COMMIT */
insert into chart_data values ('English',67)
insert into chart_data values ('Physics',67)
insert into chart_data values ('Chemistry',67)
insert into chart_data values ('Biology',67)
insert into chart_data values ('C',67)
/* Randomize mark values - Needs COMMIT */
update chart_data set marks=TRUNC(DBMS_RANDOM.value(40,99))

Extract chart data through JDBC Connection


In this step, we establish a JDBC connection to the database we want to connect  to and run a SQL against the table where the chart data is stored. This part of the code will utilize ojdbc6.jar file. You need to provide the right database credentials / SQL query for this step to work properly. If you are running a different version of Oracle (not 11g R2), then pick the right JAR file that works for you.

DefaultCategoryDataset population through JDBC


In this step, we add the data extracted from the table into DefaultCategoryDataset object. This steps completes the formulation of the data that is required to create the chart for us.

Create Bar Chart Object


In this step, we will use the “createBarChart” method in ChartFactory class to create a logical chart object. We will pass the DefaultCategoryDataset object to this method and also specify chart parameters like title, axis title , chart orientation etc.

Write Bar Chart to File


In this step we create a File object and write the chart object created out of the last step to a PNG image file. We also specify and control the width and height of the chart image. We use “ChartUtilities.saveChartAsPNG” method to write the output as PNG image.

Fully working Chart code 


The fully completed Java code example to create chart based on an Oracle table through JDBC is provided below
import java.sql.*; 
import java.io.*;
import org.jfree.data.category.DefaultCategoryDataset; 
import org.jfree.chart.ChartFactory; 
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.JFreeChart; 
import org.jfree.chart.ChartUtilities; 
public class BarChartJDBCExample {  
        
        public static void main(String[] args) throws Exception{
                
                Class.forName ("oracle.jdbc.OracleDriver"); 
                Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@//localhost:1521/xe", "hr", "hr");
                DefaultCategoryDataset my_bar_chart_dataset = new DefaultCategoryDataset();
                Statement stmt = conn.createStatement();
                try {
                        ResultSet query_set = stmt.executeQuery("select category,marks from chart_data");
                        while (query_set.next()) {
                                String category = query_set.getString("CATEGORY");
                                int marks = query_set.getInt("MARKS");
                                my_bar_chart_dataset.addValue(marks,"Mark",category);
                                }
                JFreeChart BarChartObject=ChartFactory.createBarChart("Subject Vs Marks - Bar Chart","Subject","Marks",my_bar_chart_dataset,PlotOrientation.VERTICAL,true,true,false);                  
                query_set.close();
                stmt.close(); 
                conn.close();
                int width=640; /* Width of the image */
                int height=480; /* Height of the image */                
                File BarChart=new File("output_chart.png");              
                ChartUtilities.saveChartAsPNG(BarChart,BarChartObject,width,height); 
                }
                 catch (Exception i)
                 {
            System.out.println(i);
                 }
   
        }
}        

Example output


The output produced by the code is provided below:

JFreeChart - Java JDBC Chart Example
JFreeChart - JDBC Chart Example

Exception while creating Java Chart


If you get any exceptions while creating the chart at runtime, it will be dumped back on the screen for you. Make sure you have all the JAR files in your CLASSPATH before running the code. The example is tested working if this still does not work for you, post it in the comments section. We will have a look.

2 comments:

  1. hi sir thanku very much that i got the solution by this code

    ReplyDelete
  2. Exception in thread "main" java.lang.NoSuchMethodError: org.jfree.text.TextBlock.setLineAlignment(Lorg/jfree/ui/HorizontalAlignment;)V
    at org.jfree.chart.title.TextTitle.arrangeRR(TextTitle.java:501)
    at org.jfree.chart.title.TextTitle.arrange(TextTitle.java:460)
    at org.jfree.chart.JFreeChart.drawTitle(JFreeChart.java:1300)
    at org.jfree.chart.JFreeChart.draw(JFreeChart.java:1190)
    at org.jfree.chart.JFreeChart.createBufferedImage(JFreeChart.java:1388)
    at org.jfree.chart.JFreeChart.createBufferedImage(JFreeChart.java:1368)
    at org.jfree.chart.ChartUtilities.writeChartAsPNG(ChartUtilities.java:171)
    at org.jfree.chart.ChartUtilities.saveChartAsPNG(ChartUtilities.java:308)
    at org.jfree.chart.ChartUtilities.saveChartAsPNG(ChartUtilities.java:281)
    at sacco.BarChartJDBCExample.main(BarChartJDBCExample.java:43)
    Java Result: 1
    BUILD SUCCESSFUL (total time: 2 seconds)

    ReplyDelete