Pages

Bar Chart Customization in JasperReport

Jasper Report is used to build a Report. Report may contains charts, to represent the behavior of data in pictorial form.

In this tutorial I will tell you, How to customize charts properties through Java code instead of hard-coding property to "jrxml" file.

As we know that every chart has a property called "Customizer Class" that can take the reference of Java classes. we use this property to format the chart.

To set  the chart property through Java code we require following steps - 

1. First we have to create a "Java class" and put the formatting code inside this class

2. compile and package this class to "jar" file.

3. add  "jar" file to 'class path' of invoking program that will run the jasper.

Here I am providing a small sample code for setting the property of Bar Chart through Java code, that you can used to format the charts.


public class BarChart implements JRChartCustomizer {
 @SuppressWarnings("deprecation")
 public void customize(JFreeChart chart, JRChart jasperChart) {
  CategoryPlot plot = chart.getCategoryPlot();
                BarRenderer render = (BarRenderer) plot.getRenderer();
                Font titleFont = new Font("Helvetica", Font.BOLD, 7);
  Font font = new Font("Helvetica", Font.PLAIN, 6);
  Font subFont = new Font("Helvetica", Font.ITALIC, 7);

  plot.setNoDataMessage("No Data Available");
  plot.setNoDataMessageFont(font);
  plot.setDomainGridlinesVisible(false);
  plot.setRangeGridlinesVisible(false);
  
  int a = plot.getDataset().getRowCount();
   
                if(a==1){
   render.setSeriesPaint(0, Color.BLACK);
  }
    
  chart.setBorderVisible(false);
  chart.setBorderPaint(Color.WHITE);
    
}



Now compile this code and pack to "jar" file and add to the "classpath" and use this class in "Customizer Class" property of chart.

If you have any query feel free to ask.

No comments:

Post a Comment