下载jar包并添加到项目:jcommon-1.0.23.jar jfreechart-1.0.19.jar
//工具类
package org.chart.demo;
import java.awt.Font;import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import org.jfree.chart.ChartFrame;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.StandardChartTheme;
public class ChartBaseUtil {
/**
* 设置图表样式(主题,标题,图例,轴向)
* 该方法用于设置中文编码,防止出现乱码
* @return StandardChartTheme
*/
public static StandardChartTheme getChartTheme() {
// 创建主题样式
StandardChartTheme standardChartTheme = new StandardChartTheme("CN");
// 设置标题字体
standardChartTheme.setExtraLargeFont(new Font("隶书", Font.BOLD, 26));
// 设置图例的字体
standardChartTheme.setRegularFont(new Font("宋书", Font.PLAIN, 22));
// 设置轴向的字体
standardChartTheme.setLargeFont(new Font("华文行楷", Font.PLAIN, 22));
return standardChartTheme;
}
/**
* 该方法用于生成报表图片
* @param chart 图表对象
* @param width 长度
* @param height 高度
* @param type (图片类型:png/jpeg)
*/
public static void creatChartPictrue(JFreeChart chart, int width, int height,
String type) {
FileOutputStream fos = null;
try {
// 把时间作为文件名
if ("png".equals(type)) {
fos = new FileOutputStream(new Date().getTime() + ".png");
ChartUtilities.writeChartAsPNG(fos, chart, width, height);
} else {
fos = new FileOutputStream(new Date().getTime() + ".jpeg");
ChartUtilities.writeChartAsJPEG(fos, chart, width, height);
}
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void show(String title,JFreeChart chart){
ChartFrame chartf = new ChartFrame(title, chart);
chartf.pack();
chartf.setVisible(true);
}
}
//生成饼状图的具体操作类
package org.chart.demo;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartFrame;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.DefaultPieDataset;
public class PieChartDemo {
public static void main(String[] args) {
ChartFactory.setChartTheme(ChartBaseUtil.getChartTheme());//处理乱码问题
DefaultPieDataset dpd = new DefaultPieDataset();//创建数据集
dpd.setValue("亚洲", 232);//添加数据
dpd.setValue("欧洲", 243);
dpd.setValue("非洲", 451);
dpd.setValue("美洲", 656);
dpd.setValue("大洋洲", 521);
JFreeChart chart = ChartFactory.createPieChart("人口比例", dpd, true,false, false);//生成报表
ChartFrame cf = new ChartFrame("人口比例", chart);
cf.pack();
cf.setVisible(true);
ChartBaseUtil.creatChartPictrue(chart, 800, 1000,"jpeg");//生成图片
}
}