import java.awt.Color;
import java.awt.Font;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartFrame;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.general.DefaultPieDataset;
public class CreatePieChart {
private static JFreeChart chart;
private static DefaultPieDataset dataset;
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//步骤1:创建XYDataset对象(准备数据)
createDataset();
//步骤2:根据Dataset 生成JFreeChart对象,以及做相应的设置
createChart();
//步骤3:将JFreeChart对象输出到文件,Servlet输出流等
saveAsFile(chart, "D:\\PieXY.png", 600, 400);
//显示
ChartFrame frame = new ChartFrame("BarChart Tesing!", chart);
frame.pack();
frame.setVisible(true);
}
/**
* Create DataSet
*/
private static void createDataset() {
dataset = new DefaultPieDataset();
double[][] data = new double[][] {{1, 2, 3, 4, 5},{7, 9, 14, 21, 31}};
String[] rowKeys = {"合格","不合格"};
String[] columnKeys = {"第一种","第二种","第三种","第四种","第五种"};
Double d= 0.0;
for (int j = 0; j < columnKeys.length; j++) {
for (int i = 0; i < rowKeys.length; i++) {
d = d + data[i][j];
}
dataset.setValue(columnKeys[j], d);
}
}
/**
* 饼图
*/
public static void createChart() {
chart = ChartFactory.createPieChart("饼状图", dataset, true, true, true);
PiePlot plot = (PiePlot)chart.getPlot();
plot.setBackgroundPaint(new Color(238, 244, 255));//设置图表的颜色
chart.setBackgroundPaint(Color.white);
setChartFont();
}
/**
* Save chart to File
* @param chart
* @param outputPath
* @param weight
* @param height
*/
public static void saveAsFile(JFreeChart chart, String outputPath,
int weight, int height) {
FileOutputStream out = null;
try {
File outFile = new File(outputPath);
if (!outFile.getParentFile().exists()) {
outFile.getParentFile().mkdirs();
}
out = new FileOutputStream(outputPath);
//保存为PNG
ChartUtilities.writeChartAsPNG(out, chart, weight, height);
// 保存为JPEG
// ChartUtilities.writeChartAsJPEG(out, chart, weight, height);
out.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
// do nothing
}
}
}
}
/**
* 图标乱码解决
*/
private static void setChartFont() {
Font title = new Font("楷体", Font.PLAIN, 15);
Font f = new Font("楷体", Font.PLAIN, 12);
//title(标题),
TextTitle textTitle = chart.getTitle();
textTitle.setFont(title);
//获得图表区域对象
PiePlot plot = (PiePlot)chart.getPlot();
plot.setLabelFont(f);
//legend(图释)
chart.getLegend().setItemFont(f);
}
}
运行得到的图片: