Fixed series color for specific series labels in Jasper jfree charts

We often face the situation where it has been asked to implement specific series color for each particular series in the different charts of jasper. Thus,here I am trying to provide solution for same:

Create two jasper reports one to publish pie chart and other to publish stacked bar chart.

In pie chart,

There are series and count values required in pie chart:

1

Let us suppose for the above mentioned pie chart we need following color customisation for each series label i.e,

  • Series1 – green
  • Series2 –orange
  • Series3- purple
  • Series4- dark blue

 

In order to achieve this, we can write custom code in java as follows:

public class PiePlotEnclosingReport implements JRChartCustomizer {

             public void customize(JFreeChart chart, JRChart jasperChart) {

plot.setSectionPaint(“seies1”, new Color(63, 156, 53));

plot.setSectionPaint(“seies2”, new Color(0, 152, 219));

plot.setSectionPaint(“seies3”, new Color(140, 24, 154));

plot.setSectionPaint(“seies4”, new Color(233, 131, 0));

}

}

Create jar file of the java code and add it in chart customiser property of chart in the format: ‘packagename.classname’ as follows:-

Refer the screenshot:

2

3

Check the result, on executing report. It will be shown as in the above screenshot. One can very well  identify how the colors for each series type got changed through the chart customiser code we have used.

Similarly, we can customise the series color in stacked bar chart using following piece of code:

public class StackedBarChart implements JRChartCustomizer {

       public void customize(JFreeChart chart, JRChart jasperChart) {
       CategoryItemRenderer renderer = chart.getCategoryPlot().getRenderer();

              CategoryDataset catDS = chart.getCategoryPlot().getDataset();

              Color seriesColor = null;

              for (int i = 0; i < catDS.getRowCount(); i++) {

                     if (catDS.getRowKey(i).toString().equalsIgnoreCase(“series1”)) {

                           seriesColor = new Color(255, 175, 175);

                     } else if (catDS.getRowKey(i).toString()

                                  .equalsIgnoreCase(“series2”)) {

                           seriesColor = new Color(166, 25, 46);

                     } else if (catDS.getRowKey(i).toString()

                                  .equalsIgnoreCase(“series3”)) {

                           seriesColor = new Color(63, 156, 53);

                     } else if (catDS.getRowKey(i).toString()

                                  .equalsIgnoreCase(“series4”)) {

                           seriesColor = new Color(16, 24, 32);

                     }

       renderer.setSeriesPaint(catDS.getRowIndex(catDS.getRowKey(i)),

                                  seriesColor);

              }

}

}

Hope it helps!!

Thanks,

Nisha Sahu

BI Developer

 

 

 

Leave a Reply