How to set Locale to labels in Bar Chart?

2019-07-08 21:14发布

问题:

I am displaying a bar chart and trying to have the labels above bars displayed in correct locale (they are floats). I am developing in JasperSoft Studio 6.2.0. I set the global and/or the report (execution-time) locale to en_US, but the labels are still displayed in my Windows locale (nl_NL). I then set the label expression to

new DecimalFormat("#,##0.0##;(#,##0.0##-)").format($F{Hours})

but it's still in Windows locale. Only when I explicitly set the label expression to en_US locale:

NumberFormat.getInstance(Locale.US).format($F{Hours})

do I get the correct result. At other places (TextFields), setting the format pattern (e.g. to "#,##0.0##;(#,##0.0##-)") leads to the correct locale being applied. In bar chart settings, there is no way to specify the pattern in the same fashion, that's why I am trying to do that in code.

Is this a bug or am I missing something?

回答1:

Yes I verified, jasper reports do not use its $P{REPORT_LOCALE} when generating the chart and I would almost consider it a bug. They use metods to generate the chart that does not support passing the Locale, but they could automatically generate customizers with correct locale.

To get desired Locale in chart label your options are.

Set default locale of the entire application.

Locale.setDefault(Locale.US);

see Setting java locale settings for other methods as passing parameter when launching.

If you only want to change the Locale of the label in your chart you need to create a JRChartCustomizer

Example for BarChart

public class MyLocaleCustomizer implements JRChartCustomizer{
    @Override
    public void customize(JFreeChart chart, JRChart jrchart) {
        CategoryPlot plot = (CategoryPlot) chart.getPlot();
        StandardCategoryItemLabelGenerator lg = new StandardCategoryItemLabelGenerator("{2}",NumberFormat.getNumberInstance(Locale.US));
        plot.getRenderer().setBaseItemLabelGenerator(lg);
    }
}

In jrxml

<barChart>
    <chart customizerClass="MyLocaleCustomizer">
        ..
    </chart>
    ..
</barChart>