闲来无事,就学学报表技术,目前找到一款开源JFreeChart,遂写下最常用的柱状图与饼状图以作记录。
导入jar包:
1、jfreechart-1.0.14.jar
2、jcommon-1.0.17.jar
其他不解释 直接看代码
package jfreechart;
import java.awt.Font;
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.axis.CategoryAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;
public class TestJfreeChart {
public static void main(String[] args) throws Exception {
//显示柱状图
showBarChart();
//显示饼状图
showPieChart();
}
private static void showBarChart() throws IOException,
FileNotFoundException {
CategoryDataset dataset = getDataSet2();
JFreeChart barChart = ChartFactory.createBarChart3D("柱状图", "分组", "人数",
dataset,PlotOrientation.VERTICAL, true, true, true);
CategoryPlot plot = (CategoryPlot) barChart.getPlot();
CategoryAxis domainAxis = plot.getDomainAxis();
ValueAxis rangeAxis = plot.getRangeAxis();
Font font = new Font("微软雅黑", Font.BOLD, 12);
barChart.getTitle().setFont(font );
barChart.getLegend().setItemFont(font);
domainAxis.setLabelFont(font);
domainAxis.setTickLabelFont(font);
rangeAxis.setLabelFont(font);
rangeAxis.setTickLabelFont(font);
ChartUtilities.writeChartAsJPEG(new FileOutputStream("C:/bar.jpg"),
barChart, 1000, 700);
ChartFrame frame = new ChartFrame("柱状图", barChart);
frame.pack();
frame.setVisible(true);
}
private static CategoryDataset getDataSet2() {
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
dataset.addValue(78, "", "C++组");
dataset.addValue(120, "", "JAVA组");
dataset.addValue(65, "", "JS组");
dataset.addValue(20, "", "数据库组");
dataset.addValue(5, "", "需求组");
return dataset;
}
private static void showPieChart() throws Exception {
DefaultPieDataset dataset = getDataSet();
JFreeChart pieChart = ChartFactory.createPieChart("人员分布图", dataset, true, true, true);
PiePlot plot = (PiePlot) pieChart.getPlot();
Font font = new Font("微软雅黑", Font.BOLD, 12);
plot.setLabelFont(font);
pieChart.getLegend().setItemFont(font);
pieChart.getTitle().setFont(font);
ChartUtilities.writeChartAsJPEG(new FileOutputStream("C:/pie.jpg"),
pieChart, 1000, 700);
ChartFrame frame = new ChartFrame("测试", pieChart);
frame.pack();
frame.setVisible(true);
}
private static DefaultPieDataset getDataSet() {
DefaultPieDataset dataset = new DefaultPieDataset();
dataset.setValue("C++组", 78);
dataset.setValue("JAVA组", 120);
dataset.setValue("JS组", 65);
dataset.setValue("数据库组", 20);
dataset.setValue("需求组", 5);
return dataset;
}
}
生成的效果图:
算了,不展示图片了。真心受不了iteye的上传附件速度,简直是坑爹………………