December 02, 2006

How to use ChartCustomizer

 

JasperReports use jFreeChart as a charting library. However many features in jFreeChart are not yet supported in JasperReports. With the help of customizer, you can fully control jFreeChart.

I took me quite a while to learn how to customize the jFreeChart in JasperReports.For example, we cannot change the size of bars in BarChart, or we cannot add a complicated dynamic subtitle.
Like scriptlets, Customizer is automatically invoked during the filling process.
Your own customizer class must implement net.sf.jasperreports.engine.JRChartCustomizer interface. This interface has only one method customize(org.jfree.chart.JFreeChart chart, JRChart jasperChart).

Here is one example:
















ConsumptionChartCustomizer.java




package com.db.report.jasper.custom.consumptionreport.style;



import java.awt.BasicStroke;

import java.awt.Color;

import java.awt.Font;

import java.sql.Connection;

import java.sql.SQLException;



import net.sf.jasperreports.engine.JRAbstractChartCustomizer;

import net.sf.jasperreports.engine.JRChart;



import org.apache.log4j.Logger;

import org.jfree.chart.JFreeChart;

import org.jfree.chart.axis.CategoryAxis;

import org.jfree.chart.axis.NumberAxis;

import org.jfree.chart.block.BlockBorder;

import org.jfree.chart.plot.CategoryPlot;

import org.jfree.chart.renderer.category.StackedBarRenderer;

import org.jfree.chart.title.LegendTitle;

import org.jfree.chart.title.TextTitle;

import org.jfree.chart.title.Title;

import org.jfree.data.category.DefaultCategoryDataset;

import org.jfree.ui.HorizontalAlignment;

import org.jfree.ui.RectangleEdge;

import org.jfree.ui.RectangleInsets;



import com.db.misportal.util.ConnectionPool;

import com.db.report.jasper.custom.consumptionreport.dataset.ODBCDataset;



public class ConsumptionChartCustomizer extends JRAbstractChartCustomizer {

 /** Default Constanst */

 protected static final java.awt.Font HEADER_FONT = new java.awt.Font(

   "Arial", Font.BOLD + Font.ITALIC, 14);



 protected static final Color HEADER_COLOR = new Color(0x000x000xDE);



 protected static final float BAR_WIDTH = 0.03f;



 protected static final java.awt.Font TITLE_FONT = new java.awt.Font(

   "Arial", Font.BOLD, 8);



 protected static final Color TITLE_COLOR = new Color(0x000x00128);



 protected static final java.awt.Font TICKET_FONT = new java.awt.Font(

   "Arial", Font.PLAIN, 8);



 protected static final java.awt.Font LEGEND_FONT = new java.awt.Font(

   "Arial", Font.PLAIN, 8);



 protected static final java.awt.Color GRID_COLOR = new java.awt.Color(00,

   0);



 private final static String[] DEFAULT_MONTH_ABBREVIATION = "J""F""M",

   "A"" M"" J"" J "" A"" S""O""N""D" };



 protected static final String DEFAULT_TITLE = "Default Title";



 protected static final String DEFAULT_SUB_TITLE = null;



 protected static final String DEFAULT_DOMAIN_AXIS_LABEL = null;



 protected static final String DEFAULT_RANGE_AXIS_LABEL = null;



 protected static final RectangleEdge DEFAULT_LEGEND_POSITION = RectangleEdge.TOP;



 protected JFreeChart chart;



 private Title subTitle = null;



 private boolean hasSubTitle = false;



 private boolean hasLegend = false;



 protected static final RectangleEdge DEFAULT_SUBTITLE_POSITION = RectangleEdge.BOTTOM;



 protected static final HorizontalAlignment DEFAULT_SUBTITLE_HORIZONTAL_ALIGNMENT = HorizontalAlignment.LEFT;



 public void customize(JFreeChart chart, JRChart jrChart) {



  _log.info("customize jFreeChart ...");

  this.chart = chart;



  /* Set Chart Title */

  try {

   TextTitle title = chart.getTitle();

   title.setHorizontalAlignment(HorizontalAlignment.LEFT);

  catch (NullPointerException e) {

  }



  /* Chart Properties */

  chart.setBackgroundPaint(Color.white);

  chart.setBorderPaint(new Color(192192192));

  chart.setBorderVisible(true);

  chart.setBorderStroke(new BasicStroke(0.001f));

  chart.setPadding(new RectangleInsets(1111))// top,left,bottom,right



  /* Legend Properties */

  hasLegend = true;

  try {

   LegendTitle legend = chart.getLegend();

   legend.setItemFont(LEGEND_FONT);

   legend.setBorder(BlockBorder.NONE);

   legend.setPosition(DEFAULT_LEGEND_POSITION);

  catch (NullPointerException e) {

   hasLegend = false;

  }



  /* Chart subtitle */

  try {

   int subTitleIndex = 0;

   if (hasLegend) {

    subTitleIndex = 1;

   else {

    subTitleIndex = 0;

   }



   hasSubTitle = true;

   subTitle = chart.getSubtitle(subTitleIndex);

   setSubTitlePosition(DEFAULT_SUBTITLE_POSITION);

   setSubTitleHorizontalAlignment(DEFAULT_SUBTITLE_HORIZONTAL_ALIGNMENT);

  catch (IllegalArgumentException e) {

   hasSubTitle = false;

   subTitle = null;

   _log.debug("This chart has no subtitle.");

  }



  /* Axis: Ticket Label + Line */

  try {

   CategoryPlot plot = chart.getCategoryPlot();

   NumberAxis numberAxis = (NumberAxisplot.getRangeAxis();

   numberAxis.setTickLabelFont(TICKET_FONT);

   numberAxis.setTickLabelPaint(Color.black);

   numberAxis.setAxisLinePaint(Color.black);

   numberAxis.setAxisLineStroke(new BasicStroke(0.001f));

   numberAxis.setTickMarkPaint(GRID_COLOR);

   numberAxis.setTickMarkStroke(new BasicStroke(0.001f));

   numberAxis.setTickMarkOutsideLength(3f);



   CategoryAxis categoryAxis = (CategoryAxisplot.getDomainAxis();

   categoryAxis.setTickLabelFont(TICKET_FONT);

   categoryAxis.setTickLabelPaint(Color.black);

   categoryAxis.setAxisLinePaint(Color.black);

   categoryAxis.setAxisLineStroke(new BasicStroke(0.001f));

   categoryAxis.setAxisLineVisible(false);

   categoryAxis.setTickMarkPaint(GRID_COLOR);

   categoryAxis.setTickMarkStroke(new BasicStroke(0.001f));

   categoryAxis.setTickMarkOutsideLength(3f);

   categoryAxis.setTickMarkInsideLength(1f);



   // plot.setBackgroundPaint(Color.gray);

   /* Grid */

   // plot.setRangeGridlinesVisible(false);

   plot.setRangeGridlinePaint(GRID_COLOR);

   plot.setRangeGridlineStroke(new BasicStroke(0.001f));

   plot.clearRangeMarkers();



   /* Outline */

   plot.setOutlinePaint(null);



   /* Unit */

   numberAxis

     .setStandardTickUnits(NumberAxis.createIntegerTickUnits());



   StackedBarRenderer renderer = (StackedBarRendererplot

     .getRenderer();

   renderer.setMaximumBarWidth(BAR_WIDTH);

   renderer.setDrawBarOutline(true);

   renderer.setOutlinePaint(Color.black);

   renderer.setOutlineStroke(new BasicStroke(0.00001f));



   /* Series Color - dont need it any more - we set color in iReport */

   // renderer.setSeriesPaint(0, new Color(153, 153, 255));

   // renderer.setSeriesPaint(1, new Color(153, 51, 102));

   // renderer.setSeriesPaint(2, new Color(255, 255, 204));

   // renderer.setSeriesPaint(3, new Color(204, 255, 255));

  catch (NullPointerException e) {

  }

 }



 /**

  * Set query with default month abbreviation

  

  @param query

  */

 protected void setQuery(String query) {



  this.setQuery(query, DEFAULT_MONTH_ABBREVIATION);

 }



 /**

  * Set Chart Query : execute query and set plot dataset

  

  @param query

  @param month_abbreviation

  */

 protected void setQuery(String query, String[] month_abbreviation) {

  Connection conn = null;

  DefaultCategoryDataset dataset = null;



  try {

   conn = ConnectionPool.getConnection();

   dataset = new ODBCDataset(conn, query);

  catch (SQLException e) {

   e.printStackTrace();

  catch (com.db.report.jasper.custom.common.dataset.NullDatasetException e) {

   _log.debug("Empty dataset...Hide chart");

   this.hide();



  catch (ClassNotFoundException e) {

   e.printStackTrace();

  }



  CategoryPlot plot = chart.getCategoryPlot();

  plot.setDataset(dataset);

 }



 /**

  * Set chart title

  

  @param strTitle

  */

 public void setTitle(String strTitle) {

  TextTitle title = chart.getTitle();



  if (title == null) {

   chart.setTitle(strTitle);

  else {

   title.setText(strTitle);

  }

 }



 /**

  * Set Legend Position

  

  @param position

  */

 public void setLegendPosition(RectangleEdge position) {

  try {

   LegendTitle legend = chart.getLegend();

   legend.setPosition(position);

  catch (NullPointerException e) {

  }

 }



 /**

  * Make chart invisible

  

  */

 public void hide() {

  CategoryPlot plot = chart.getCategoryPlot();

  NumberAxis numberAxis = (NumberAxisplot.getRangeAxis();

  numberAxis.setVisible(false);

  CategoryAxis categoryAxis = (CategoryAxisplot.getDomainAxis();

  categoryAxis.setVisible(false);

  plot.setRangeGridlinesVisible(false);

 }



 /**

  * Set Subtitle Position

  

  @param position

  */

 public void setSubTitlePosition(RectangleEdge position) {

  if (hasSubTitle && subTitle != null) {

   subTitle.setPosition(position);

  }

 }



 /**

  * Set Subtitle text

  

  @param text

  */

 public void setSubTitleText(String text) {

  if (hasSubTitle && subTitle != null) {

   ((TextTitlesubTitle).setText(text);

  }

 }



 /**

  * Set Subtitle Horizontal Aligment (LEFT,RIGHT,CENTER)

  

  @param align

  */

 public void setSubTitleHorizontalAlignment(HorizontalAlignment align) {



  if (hasSubTitle && subTitle != null) {

   subTitle.setHorizontalAlignment(align);

  }

 }



 /** Logger */

 static Logger _log = Logger.getLogger(ConsumptionChartCustomizer.class);

}






That's so far for today!

15 responses:

jaspiones said...

In the Ireport, how I set the Customizer class property?

DEEPak Chhatani said...

Ya where do i save this class and set the customizer class property

Anonymous said...

Make a list of your nutrition chart involving juice and
fruits at the top followed by green vegetables and milk products.
' The picture is just as worrying for youngsters - by 2010, it's predicted 22 per cent of girls and 19 per
cent of boys between the ages of two and 15 will be obese, with
girls under 11 at particular risk. Stretching will
help you prevent injuries and it will help you loosen
up your muscles.

Review my web blog :: fitness tips and workouts

Anonymous said...

I also Love playing Online Games, Contest and Challenges.
It seems like the internet today is almost entirely full of nothing but funny pictures and
videos that people use to pass their days. Locate a respected joke internet site that allows you to make use of the offered
jokes which means you won't need to worry about email viruses.

My web page; http://makingofamillionaire.com/

Anonymous said...

Hurrah, thatís what I was exploring for, what a stuff!
existing here at this weblog, thanks admin of this site.


My website - Additional Info

Anonymous said...

The new tablet would be a further extension of these concepts and yet another step into the future of computing for Apple.
The promotion of good health is necessary to ensure that
people are healthy, wealthy and wise. It the radio was the only one that used to deliver
the days news and weather updates.

Have a look at my blog Latest Daily News

Anonymous said...

December is such a special month of the year - quality time
with family, exchanging gifts, and sumptuous food all
month long. Don't jump cold, warm up first until you break a light sweat. If you have never exercised in the morning, then we urge you to try it at least for one week.

Feel free to surf to my homepage - vonline.vrozetke.com

Anonymous said...

The fitness tips for motivation we've been discussing can be very powerful if you use them. One last thing that isn't mandatory but recommended
is to set up a Pay - Pal account to process your payments.

Pencil in at least three workouts a week on your calendar.


my blog post: fitnesstipsonly.Com

Anonymous said...

A lot of us who are under constant pressure tend to
eat too much and do not take good care of their bodies.
Men can follow these health and fitness tips to lose weight and get healthy and fit.
These tips are followed by every pregnant woman all around the world
but remember whatever you do, you should first check with your gynecologist so
that there is no complication in your pregnancy.

Also visit my website Read Much more

Anonymous said...

Hiya! Quick question that's completely off topic. Do you know how to make your site mobile friendly? My blog looks weird when browsing from my iphone4. I'm trying to
find a template or plugin that might be able to fix this
problem. If you have any recommendations, please share.
With thanks!

Here is my homepage :: Biotechnology and Bioengineering

Anonymous said...

Far too many children become the victims of abuse, neglect, or abandonment and
then sadly, often they become wards of the court who will eventually determine their fate.

The effects of what they see, read and hear are having a devastating affect on our society today.
Thus they can choose from the many available sources.


Feel free to visit my blog :: Latest Daily News

Anonymous said...

Instead of eating to make yourself feel better find other methods to cope.

According to experts, water and juices from various kinds
of fruit are essential part of good diet. Yet, before you can
get to this point, you first have to make a
start.

My website - fitness tips and quotes

Anonymous said...

great put up, very informative. I wonder why the opposite specialists of this sector don't realize this. You must continue your writing. I am confident, you've
a great readers' base already!

Here is my blog post; diet plans

Anonymous said...

They are casual gaming experiences as opposed to hardcore gaming.
The other day, I was talking with an acquaintance who stated that "There are many issues in modern society that bother me, I feel that everybody is a zombie, people seem to be blind to what actually happening around them, newspaper headlines are full of celebrity nonsense, everything seems designed to distract people from the real world, everything seems so detached. What's nice about About Angry birds is that it has a very basic idea and concept.

My web site angry birds online spielen

Unknown said...

Nicely explained.for more info about jasper customizer class,view this related post Jasper Customizer class