如果使用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的字體就行了.
不過這種方法只適用于中文操作系統,因為已經有中文字體了.要想在非中文系統上用怕是要在程序中帶上一個中文字體庫,然后再調用該字庫.