`
zuiyanwangyue
  • 浏览: 164587 次
  • 性别: Icon_minigender_1
  • 来自: 河北
社区版块
存档分类
最新评论

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

阅读更多

项目中图表制作时使用到了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()));
		}
	}
}

 

分享到:
评论
3 楼 sdh5724 2011-05-24  
zuiyanwangyue 写道
sdh5724 写道
头疼, 这也会甚为艰难。  多学习才是王道。

呵呵 希望老兄多多指点


多看看代码那些破玩意,比看书要好。
2 楼 zuiyanwangyue 2011-05-24  
sdh5724 写道
头疼, 这也会甚为艰难。  多学习才是王道。

呵呵 希望老兄多多指点
1 楼 sdh5724 2011-05-23  
头疼, 这也会甚为艰难。  多学习才是王道。

相关推荐

Global site tag (gtag.js) - Google Analytics