六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 71|回复: 0

JFreeChart由1.0.10升级到1.0.13后的乱码解决方案

[复制链接]

升级  98%

11

主题

11

主题

11

主题

童生

Rank: 1

积分
49
 楼主| 发表于 2013-2-6 08:43:15 | 显示全部楼层 |阅读模式
项目中图表制作时使用到了JfreeChart,最近在升级版本时遭遇到了中文乱码问题,当然这并非传说中的JSP编码造成的,网上baidu了半天,徒劳无果,不得已只能自己分析解决。
 
过程甚为艰难,在此不予赘述,仅记下问题根源及解决方案,以飨同“僚”。
 
根源:从1.0.11版本起,jfreechart引入了一个ChartTheme(图表主题)的概念,并提供了标准的实现(org.jfree.chart.StandardChartTheme),标准图表主题中定义了制作图表时所使用的四种字体(超大、大、常规、小)。public StandardChartTheme(String name) {        if (name == null) {            throw new IllegalArgumentException("Null 'name' argument.");        }        this.name = name;        this.extraLargeFont = new Font("Tahoma", Font.BOLD, 20);        this.largeFont = new Font("Tahoma", Font.BOLD, 14);        this.regularFont = new Font("Tahoma", Font.PLAIN, 12);        this.smallFont = new Font("Tahoma", Font.PLAIN, 10);        ……}中文乱码正是由于Tahoma这种字体不能正常解码造成的。
解决方案:在系统启动时(在使用jfreechart之前)将标准图表主题中的字体进行覆盖设置即可。我的一种思路是定义一个Java Bean(系统开发使用到了Spring)并它实现org.springframework.beans.factory.InitializingBean接口,然后在afterPropertiesSet方法中进行jfreechart的配置,只要随后在需要时把它当做一个普通的bean配置到spting的配置文件中就可以了,源码如下:
 
public class JFreeChartChineseEnvConfiguration implements InitializingBean{public void afterPropertiesSet() throws Exception {ChartTheme chartTheme=ChartFactory.getChartTheme();if(chartTheme instanceof StandardChartTheme){StandardChartTheme sct=(StandardChartTheme)chartTheme;Font extraLarge=sct.getExtraLargeFont();if(extraLarge!=null) sct.setExtraLargeFont(new Font("宋体",extraLarge.getStyle(),extraLarge.getSize()));Font large=sct.getLargeFont();if(large!=null) sct.setLargeFont(new Font("宋体",large.getStyle(),large.getSize()));Font regular=sct.getRegularFont();if(regular!=null) sct.setRegularFont(new Font("宋体",regular.getStyle(),regular.getSize()));Font small=sct.getSmallFont();if(small!=null) sct.setSmallFont(new Font("宋体",small.getStyle(),small.getSize()));}}}
 
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表