由于JFreeChart组件的版本、操作平台、JDK的设置等因素,在使用JFreeChart组件时可能会出现中文乱码的现象。遇到此问题时,可通过设置文字的字体来解决问题。在此提供以下三种种解决此问题的方法。
一、设置主题的样式(强烈推荐)
在制图前,创建主题样式并制定样式中的字体,通过ChartFactory的setChartTheme()方法设置主题样式。
//创建主题样式
StandardChartTheme standardChartTheme=new StandardChartTheme("CN");
//设置标题字体
standardChartTheme.setExtraLargeFont(new Font("隶书",Font.BOLD,20));
//设置图例的字体
standardChartTheme.setRegularFont(new Font("宋书",Font.PLAIN,15));
//设置轴向的字体
standardChartTheme.setLargeFont(new Font("宋书",Font.PLAIN,15));
//应用主题样式
ChartFactory.setChartTheme(standardChartTheme);
二、更换JFreeChart的jar包版本
目前最新的版本是jfreechart-1.0.19.jar,替换为jfreechart-1.0.10.jar则可以正常显示。(一般在10以上的都有可能出现这个问题)
三、制定乱码文字的字体
使用JFreeChart绘制图表的时候,如果使用默认的字体会导致图标中的汉字显示为乱码。解决方法如下:
JFreeChart是用户使用该库提供的各类图标的统一接口,JFreeChart主要由三个部分构成:title(标题),legend(图释),plot(图表主体)。三个部分设置字体的方法分别如下:
1.Title
TextTitle textTitle = freeChart.getTitle();
textTitle.setFont(new Font("宋体",Font.BOLD,20));
2.Legent
LegendTitle legend = freeChart.getLegend();
if (legend!=null) {
legend.setItemFont(new Font("宋体", Font.BOLD, 20));
}
3.Plot
对于不同类型的图表对应Plot的不同的实现类,设置字体的方法也不完全相同。
对于使用CategoryPlot的图表(如柱状图):
CategoryPlot plot = (CategoryPlot)freeChart.getPlot();
CategoryAxis domainAxis = plot.getDomainAxis();//(柱状图的x轴)
domainAxis.setTickLabelFont(new Font("宋体",Font.BOLD,20));//设置x轴坐标上的字体
domainAxis.setLabelFont(new Font("宋体",Font.BOLD,20));//设置x轴上的标题的字体
ValueAxis valueAxis = plot.getRangeAxis();//(柱状图的y轴)
valueAxis.setTickLabelFont(new Font("宋体",Font.BOLD,20));//设置y轴坐标上的字体
valueAxis.setLabelFont(new Font("宋体",Font.BOLD,20));//设置y轴坐标上的标题的字体
CategoryPlot plot = (CategoryPlot)freeChart.getPlot();
CategoryAxis domainAxis = plot.getDomainAxis();//(柱状图的x轴)
domainAxis.setTickLabelFont(new Font("宋体",Font.BOLD,20));//设置x轴坐标上的字体
domainAxis.setLabelFont(new Font("宋体",Font.BOLD,20));//设置x轴上的标题的字体
ValueAxis valueAxis = plot.getRangeAxis();//(柱状图的y轴)
valueAxis.setTickLabelFont(new Font("宋体",Font.BOLD,20));//设置y轴坐标上的字体
valueAxis.setLabelFont(new Font("宋体",Font.BOLD,20));//设置y轴坐标上的标题的字体
对于使用PiePlot的图标(如饼状图):
PiePlot plot = (PiePlot)freeChart.getPlot();
plot.setLabelFont(new Font("宋体",Font.BOLD,15));