gpt4 book ai didi

java - 如何在图表定制器中读取Jasperreports传递的Locale?

转载 作者:行者123 更新时间:2023-11-30 06:38:25 24 4
gpt4 key购买 nike

(我的问题基于 2016 年 4 月的 this 硬编码示例,并且正在寻求更新的动态答案,因为“bug”已修复 - 定制器中没有可用的区域设置)

/* -Hardcoded example */
getNumberInstance(Locale.US)); //"Locale.US" is hardcoded rather than using the locale set in the report

目标:将 jasper 报告中设置的区域设置传递到图表并使用图表定制器进行读取。

  • 既然报告区域设置不可用的错误已经是fixed (see here),我该如何正确读取报告区域设置呢? ?

问题:在定制器类(用 Java 编写)中,此命令不包含任何内容:JRParameter.REPORT_LOCALE。

public class AssetsChartMod implements JRChartCustomizer {

public void customize(JFreeChart chart, JRChart jasperChart) {

/* ----> */
System.out.println( JRParameter.REPORT_LOCALE ); // PRINTS NOTHING

最佳答案

不幸的是,我们无法从JRChart对象获取报表的参数。这将是从参数映射中获取区域设置的最简单方法。

但是我们可以执行这个技巧:

  1. jrxml文件中为图表添加属性区域设置

带有图表声明的 jrxml 文件片段:

<pie3DChart>
<chart customizerClass="ru.alex.PieChartCustomizer" theme="aegean">
<reportElement positionType="Float" x="0" y="0" width="100" height="100">
<propertyExpression name="locale"><![CDATA[((java.util.Locale) ($P{REPORT_PARAMETERS_MAP}.get("REPORT_LOCALE"))).toString()]]></propertyExpression>
</reportElement>

该属性只能是String类型,这就是我在表达式中执行强制转换的原因。

  • JRChartCustomizer 类中,我在以下帮助下获取了该属性 JRChart.getPropertiesMap()方法。
  • 在我的例子中,包名称是ru.alex

    public class PieChartCustomizer implements JRChartCustomizer {

    private static final String LOCALE_PROPERTY = "locale"; // the same name as at jrxml file
    private static final Locale DEFAULT_LOCALE = Locale.ENGLISH;

    @Override
    public void customize(JFreeChart chart, JRChart jasperChart) {
    PiePlot pieChart = (PiePlot) chart.getPlot();
    JRPropertiesMap map = jasperChart.getPropertiesMap();

    Locale locale = DEFAULT_LOCALE; // this is default Locale if property was not set
    if (map != null && !map.isEmpty()) {
    if (!isNullOrEmpty(map.getProperty(LOCALE_PROPERTY))) {
    locale = Locale.forLanguageTag(map.getProperty(LOCALE_PROPERTY).replace("_", "-")); // here we have Locale passed via property 'locale'. Replacement applied: en_GB -> en-GB, for example
    }
    }

    // some actions
    }

    private static boolean isNullOrEmpty(String string) {
    return string == null || string.isEmpty();
    }
    }

    瞧,我们在定制器中获得了报告的区域设置。

    关于java - 如何在图表定制器中读取Jasperreports传递的Locale?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44839441/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com