在使用JFreeChart (http://www.jfree.org/jfreechart/ )做中文的图表时,中文乱码是一个最常要处理的问题,看网上许多文章都是在JFreeChart对象上下功夫,每次都得重新设置字体,比较麻烦。其实JFreeChart为我们提供了一个通用的解决方案——ChartTheme 。
ChartTheme有一个默认的实现类StandardChartTheme ,该类提供了图表主题的默认实现,通过ChartFactory 默认将这一实现应用到所有ChartFactory所生成的JFreeChart 对象中,你可以利用ChartFactory的setChartTheme(ChartThemetheme) 方法改变这一默认实现,让所有由ChartFactory生成的图表都应用你所指定的主题。
StandardChartTheme提供如下方法来定制字体:
- public void setExtraLargeFont(Fontfont)
- public void setLargeFont(Fontfont)
- public void setRegularFont(Fontfont)
- public void setSmallFont(Fontfont)
只要重写这几个方法,就可以制定出一个适合中文图表的主题了:
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(newFont("宋体", Font.PLAIN,14));
theme.setLargeFont(newFont("宋体", Font.PLAIN,14));
theme.setRegularFont(newFont("宋体", Font.PLAIN,12));
theme.setSmallFont(newFont("宋体", Font.PLAIN,10));
ChartFactory.setChartTheme(theme);
重写apply(...)方法是为了借机消除文字锯齿.VALUE_TEXT_ANTIALIAS_OFF
ChartFactory.setChartTheme(theme); 用于将该主题作为工厂的默认主题。
这样一来,以后使用ChartFactory创建图表时,都可以自动应用主题中的配置了,做到解决中文乱码和锯齿一劳永逸。
demo:
import java.awt.Font;
import java.awt.RenderingHints;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartFrame;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.StandardChartTheme;
import org.jfree.data.general.DefaultPieDataset;
public class Test1 {
public static void main(String[] args) {
DefaultPieDataset dfp = newDefaultPieDataset();
dfp.setValue("开发人员",110);
dfp.setValue("测试人员",8);
dfp.setValue("人事",4);
dfp.setValue("部门经理",8);
dfp.setValue("销售人员",15);
// 通用的中文问题解决方案
StandardChartTheme theme = newStandardChartTheme("unicode"){
public void apply(JFreeChart chart){
chart.getRenderingHints().put(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
super.apply(chart);
}
};
theme.setExtraLargeFont(newFont("宋体", Font.PLAIN,14));
theme.setLargeFont(newFont("宋体", Font.PLAIN,14));
theme.setRegularFont(newFont("宋体", Font.PLAIN,12));
theme.setSmallFont(newFont("宋体", Font.PLAIN,10));
ChartFactory.setChartTheme(theme);
JFreeChart jfreeChart =ChartFactory.createPieChart("全景人员信息图", dfp,
true, true, true);
ChartFrame chartFrame = newChartFrame("全景人员信息图", jfreeChart, true);
chartFrame.pack();
chartFrame.setVisible(true);
}
}
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请
点击举报。