如果使用JfreeChart默認(rèn)的聲明方式創(chuàng)建出來的圖表圖片上中文標(biāo)題是方框或亂碼,這個(gè)不用說肯定和字體有關(guān).接下來來看一下解決辦法.
打開doc文件里的TextTitle類你會(huì)發(fā)現(xiàn)
/** The default font. */
public static final Font DEFAULT_FONT = new Font("SansSerif", Font.BOLD,12);
JFreeChart里最后將你創(chuàng)建的實(shí)例傳給了另一個(gè)類的方法:currentTheme.apply(chart);
找到theme的頂級(jí)類StandardChartTheme你會(huì)發(fā)現(xiàn)這個(gè)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); //------------在這里它將標(biāo)題的字體設(shè)置成了事先定義好的字體,如下兩段代碼;
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); //在構(gòu)造函數(shù)里將此字體設(shè)置成了"Tahoma"
現(xiàn)在我們已經(jīng)很清楚不能正確顯示中文的原因了,如何來解決呢?
很簡(jiǎn)單:
JFreeChart chart=ChartFactory.createPieChart(titleString,pieDataset,true,true,false);
chart.getTitle().setFont(new Font("宋體", Font.BOLD,12));
我們只要重新設(shè)置TextTitle的字體就行了.
不過這種方法只適用于中文操作系統(tǒng),因?yàn)橐呀?jīng)有中文字體了.要想在非中文系統(tǒng)上用怕是要在程序中帶上一個(gè)中文字體庫(kù),然后再調(diào)用該字庫(kù).
TonyLee.