How to format to two decimal places on CategoryPlot chart

Viewed 239

I'm trying to format my report to only show 2 decimal places with percentage through my JRXML report, but even with a class customizer, it's not working and when it displays on PDF file.

My code (customizer class):

       import net.sf.jasperreports.engine.JRChart;
       import net.sf.jasperreports.engine.JRChartCustomizer;
       import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
       import org.jfree.chart.plot.CategoryPlot;
       import org.jfree.chart.renderer.category.BarRenderer;

       public void customize(JFreeChart chart, JRChart jasperChart){
        CategoryPlot barPlot = (CategoryPlot) chart.getPlot();
        BarRenderer renderer = (BarRenderer) barPlot.getRenderer();

        NumberFormat formatter = new DecimalFormat("#0.00%");
        formatter.setMinimumFractionDigits(2);
        StandardCategoryItemLabelGenerator scilg2 = new StandardCategoryItemLabelGenerator("{0} {2}", formatter);
        renderer.setItemLabelGenerator(scilg2);
       }

I already searched on every forum, but the answers didn't worked, most of them were applied to Pie chart, but that's not my case.

PS: I'm using JFreeChart 1.0.0 version and iReport 1.2.8.

2 Answers

Use the ArgumentIndex value {3}, seen here, and supply a separate percentFormatter. Using v.1.5.3, I added the following to BarChartDemo1 to get the image shown:

plot.setOrientation(PlotOrientation.HORIZONTAL);
NumberFormat percent = NumberFormat.getPercentInstance();
percent.setMinimumFractionDigits(2);
renderer.setDefaultItemLabelGenerator(
    new StandardCategoryItemLabelGenerator(
        "{0} {1} {2} {3}", NumberFormat.getInstance(), percent));
renderer.setDefaultItemLabelsVisible(true);

HORIZONTAL

I'm using JFreeChart 1.0.0 version and iReport 1.2.8.

So I have finally been able to format the numbers by using this code below—posting so if someone ends up with the same problem as I was, they can correct it.

NumberFormat formatter = new DecimalFormat("#0.00'%'");
renderer.setItemLabelGenerator(new StandardCategoryItemLabelGenerator());
StandardCategoryItemLabelGenerator base = new StandardCategoryItemLabelGenerator("{2}",formatter);
renderer.setBaseItemLabelGenerator(base);
barPlot.setRenderer(renderer);

You have to use the ArgumentIndex value {2}, and after that you need to use the method setRenderer() to send a change event to all registered listeners.

Thanks @trashgod (https://stackoverflow.com/users/230513/trashgod) for your help, I got to work around your code and display the results on previous versions of the JFreeChart.

Links:

CategoryPlot - setRenderer

AbstractCategoryItemLabelGenerator

Related