jfreechart在linux下的中文乱码
原文链接:
http://ferreousbox.iteye.com/blog/395176
这两天因为要统计报表,就用到了jfreechart组件,因为是在windows下编程,所以一直都比较正常,可没想到一放到linux下就出现了乱码,所有的中文都是显示小方块,郁闷的很,然后google了下,网络上倒是有不少的解决方案,可一一试过以后发现都不行,仍旧是乱码,或许是因为环境不同导致配置无法生效,也或许是我配置有失误,总之试了很多都无法解决乱码的问题。再者网络上介绍的都是更改系统的字体,麻烦的很,而且有误操作的可能性,而且文章都比较旧了,视乎跟不上时代的节奏了。本着自我研究的精神,google了不少的方案后大致明白应该是JRE找不到指定的字体而导致的乱码,所以当然是从字体入手,首先是看看jfreechart默认是用什么字体的,查看如下代码:
System.out.println(jfreechart.getTitle().getFont().getFamily());
SansSerif
jfreechart.getTitle().setFont(new Font("宋体", Font.BOLD, 22)); jfreechart.getTitle().setFont(new Font("宋体", Font.BOLD, 22)); Font font = new Font("宋体", Font.BOLD, 22); jfreechart.getTitle().setFont(font); // 标题 font = new Font("宋体", Font.PLAIN, 14); jfreechart.getLegend().setItemFont(font); // 列类型的文字字体 font = new Font("宋体", Font.PLAIN, 16); categoryaxis.setLabelFont(font); // x轴名称的字体 categoryplot.getRangeAxis().setLabelFont(font); // y轴名称的字体 CategoryPlot categoryplot = jfreechart.getCategoryPlot(); CategoryAxis categoryaxis = categoryplot.getDomainAxis(); font = new Font("宋体", Font.PLAIN, 12); categoryaxis.setTickLabelFont(font); // x轴上的刻度名称字体 categoryplot.getRangeAxis().setTickLabelFont(font); // y轴上的刻度名称字体 font = new Font("宋体", Font.PLAIN, 18); categoryplot.setNoDataMessage(emptyMsg); categoryplot.setNoDataMessageFont(font); // 没有数据时的提示 package test; public class ImageTester { public static void generate(String fileName) throws Exception { BufferedImage image = new BufferedImage(300, 200, BufferedImage.TYPE_INT_RGB); Graphics g = image.getGraphics(); String fontType = "宋体"; g.setFont(new Font(fontType , Font.BOLD, 22)); g.drawString("你好我好", 30, 30); g.drawString("\u5b8b\u4f53", 30, 80); ImageIO.write(image, "JPEG", new FileOutputStream(new File(fileName))); } /** * @param args */ public static void main(String[] args) throws Exception { generate(args[0]); } } linux下运行时这样运行: java test.ImageTetser /home/test.png