由于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是用户使用该库提供的各类图标的统一接口,JFreeChart主要由三个部分构成:title(标题),legend(图释),plot(图表主体)。三个部分设置字体的方法分别如下:
1.标题:
freeChart.getTitle().setFont(new Font("黑体", Font.BOLD, 20));
或
TextTitle textTitle = freeChart.getTitle();
textTitle.setFont(new Font("黑体",Font.BOLD,20));
2.图释:
LegendTitle legend = freeChart.getLegend();
if (legend!=null)
{
legend.setItemFont(new Font("宋体", Font.BOLD, 20));
}
3.图表主体:
对于不同类型的图表对应Plot的不同的实现类,设置字体的方法也不完全相同。
曲线图:
CategoryAxis valueAxis = plot.getDomainAxis();
// 设置x轴上面的字体
valueAxis.setTickLabelFont(new Font("隶书", Font.ITALIC, 12));
// 设置X轴的标题文字
valueAxis.setLabelFont(new Font("隶书", Font.ITALIC, 12));
NumberAxis numberAxis = (NumberAxis) plot.getRangeAxis();
// 设置y轴上的字体
numberAxis.setTickLabelFont(new Font("宋体", Font.PLAIN, 13));
// 设置y轴上的标题字体
numberAxis.setLabelFont(new Font("宋体", Font.PLAIN, 13));
饼图:
chart.getTitle().setFont(new Font("黑体", Font.BOLD, 20));
PiePlot piePlot = (PiePlot) chart.getPlot();
piePlot.setLabelFont(new Font("黑体", Font.BOLD, 10));
chart.getLegend().setItemFont(new Font("黑体", Font.BOLD, 10));
柱形图:
CategoryAxis domainAxis = plot.getDomainAxis();
// 设置水平底部列表
domainAxis.setLabelFont(new Font("黑体", Font.BOLD, 14));
// 设置水平底部标题
domainAxis.setTickLabelFont(new Font("黑体", Font.BOLD, 12));
// 设置锤子标题
ValueAxis rangeAxis = plot.getRangeAxis();
rangeAxis.setLabelFont(new Font("黑体", Font.BOLD, 18));
// 设置说明的字体
chart.getLegend().setItemFont(new Font("黑体", Font.BOLD, 18));
chart.getTitle().setFont(new Font("黑体", Font.BOLD, 20));
JFreeChart 解决中文乱码
猜你喜欢
转载自maosheng.iteye.com/blog/2008248
今日推荐
周排行