易客

Explore JAVA

  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  4 随笔 :: 1 文章 :: 52 评论 :: 0 Trackbacks
如果使用JfreeChart默认的声明方式创建出来的图表图片上中文标题是方框或乱码,这个不用说肯定和字体有关.接下来来看一下解决办法.

打开doc文件里的TextTitle类你会发现
 
/** The default font. */
 
public static final Font DEFAULT_FONT = new Font("SansSerif", Font.BOLD,12);


JFreeChart里最后将你创建的实例传给了另一个类的方法:currentTheme.apply(chart);

找到theme的顶级类StandardChartTheme你会发现这个apply()方法,
public void apply(JFreeChart chart) {
            
if (chart == null) {
                
throw new IllegalArgumentException("Null 'chart' argument.");
            }
            TextTitle title 
= chart.getTitle();
            
if (title != null) {
                title.setFont(
this.extraLargeFont);  //------------在这里它将标题的字体设置成了事先定义好的字体,如下两段代码;
                title.setPaint(this.titlePaint);
            }


123        private Font extraLargeFont;


294        public StandardChartTheme(String name) {
295            if (name == null) {
296                throw new IllegalArgumentException("Null 'name' argument.");
297            }
298            this.name = name;
299            this.extraLargeFont = new Font("Tahoma", Font.BOLD, 20); //在构造函数里将此字体设置成了"Tahoma"

现在我们已经很清楚不能正确显示中文的原因了,如何来解决呢?
很简单:

JFreeChart chart=ChartFactory.createPieChart(titleString,pieDataset,true,true,false);
        chart.getTitle().setFont(
new Font("宋体", Font.BOLD,12));

我们只要重新设置TextTitle的字体就行了.
不过这种方法只适用于中文操作系统,因为已经有中文字体了.要想在非中文系统上用怕是要在程序中带上一个中文字体库,然后再调用该字库.


 TonyLee.

posted on 2009-02-23 14:17 y6cn 阅读(3178) 评论(2)  编辑  收藏

评论

# re: JfreeChart标题中文乱码的解决 2009-05-13 09:15 小三文鱼
呵呵 很好哦 讲的简单易懂  回复  更多评论
  

# re: JfreeChart标题中文乱码的解决 2009-08-31 10:54 Nassir
很好....  回复  更多评论
  


只有注册用户登录后才能发表评论。


网站导航: