`

JFreeChart中文乱码和文字模糊问题的通用解决方案 | #java #chart

阅读更多

  在使用JFreeChart (http://www.jfree.org/jfreechart/ )做中文的图表时,中文乱码是一个最常要处理的问题,看网上许多文章都是在JFreeChart对象上下功夫,每次都得重新设置字体,比较麻烦。其实JFreeChart为我们提供了一个通用的解决方案——ChartTheme

 

  ChartTheme有一个默认的实现类StandardChartTheme ,该类提供了图表主题的默认实现,通过ChartFactory 默认将这一实现应用到所有ChartFactory所生成的JFreeChart 对象中,你可以利用ChartFactory的setChartTheme(ChartTheme theme) 方法改变这一默认实现,让所有由ChartFactory生成的图表都应用你所指定的主题。

 

  StandardChartTheme提供如下方法来定制字体:

  • public void setExtraLargeFont(Font font)
  • public void setLargeFont(Font font)
  • public void setRegularFont(Font font)
  • public void setSmallFont(Font font)

  只要重写这几个方法,就可以制定出一个适合中文图表的主题了:

 

StandardChartTheme theme = new StandardChartTheme("unicode") {
	public void apply(JFreeChart chart) {
		chart.getRenderingHints().put(RenderingHints.KEY_TEXT_ANTIALIASING,
				RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
		super.apply(chart);
	}
};
theme.setExtraLargeFont(new Font("宋体", Font.PLAIN, 20));
theme.setLargeFont(new Font("宋体", Font.PLAIN, 14));
theme.setRegularFont(new Font("宋体", Font.PLAIN, 12));
theme.setSmallFont(new Font("宋体", Font.PLAIN, 10));
ChartFactory.setChartTheme(theme);
 

  重写apply(...)方法是为了借机消除文字锯齿.VALUE_TEXT_ANTIALIAS_OFF

  ChartFactory.setChartTheme(theme); 用于将该主题作为工厂的默认主题。

 

  这样一来,以后使用ChartFactory创建图表时,都可以自动应用主题中的配置了,做到解决中文乱码和锯齿一劳永逸。

 

1
0
分享到:
评论
4 楼 greatghoul 2013-09-13  
hanmiao 写道
好用,我在 51CTO 上也找到了类似的解决方案,也是通过自定义 ChartFactory 的 ChartTheme 来实现的,链接在 http://developer.51cto.com/art/201112/308902.htm


这篇文章讲解的真是详细,谢谢推荐!
3 楼 hanmiao 2013-09-05  
好用,我在 51CTO 上也找到了类似的解决方案,也是通过自定义 ChartFactory 的 ChartTheme 来实现的,链接在 http://developer.51cto.com/art/201112/308902.htm
2 楼 wyzxzws 2012-03-26  
谢谢指点,好东东西!希望多多交流!
1 楼 lanhongbo 2010-08-26  
实在的好文 顶了!

相关推荐

Global site tag (gtag.js) - Google Analytics