Search code examples
jasper-reportsjfreechartdate-formatting

How to convert the number of month in the name abbreviation in Jasper Report?


I have a XY Line Chart in JasperReports and I´m using a range in my Chart for display the Months, currently i´m using this configuration and show the values from 1 to 12 in X Line:

Image of currently chart

<?xml version="1.0" encoding="UTF-8"?>
<property name="net.sf.jasperreports.customizer.class.1" value="net.sf.jasperreports.customizers.axis.DomainAxisCustomizer"/>
                    <property name="net.sf.jasperreports.customizer.1.tickUnit" value="1.0"/>
                    <propertyExpression name="net.sf.jasperreports.customizer.1.minValue"><![CDATA["1"]]></propertyExpression>
                    <propertyExpression name="net.sf.jasperreports.customizer.1.maxValue"><![CDATA["12"]]></propertyExpression>

but I need show the abbreviation of the months, like this:

1 - JAN, 2 - FEB, 3 - MAR, ...

Is there a better way to do this?


Solution

  • You can implement your own domain axis customizer like this:

    public class DomainAxisWithMonthsCustomizer extends JRAbstractChartCustomizer {
        @Override
        public void customize(JFreeChart chart, JRChart jasperChart) {
            XYPlot plot = chart.getXYPlot();
            String[] shortMonths = new DateFormatSymbols().getShortMonths();
            SymbolAxis domainAxis = new SymbolAxis("Month",
                    IntStream.rangeClosed(1, 12)
                            .mapToObj(m -> m + " - " + shortMonths[m - 1].toUpperCase())
                            .toArray(String[]::new));
            plot.setDomainAxis(domainAxis);
        }
    }
    

    And use it in your report template:

    <chart customizerClass="my.project.report.DomainAxisWithMonthsCustomizer">
    ...
    </chart>