1.jar包,jcommon.jar和jfreechart.jar,具体用哪个版本官网去down吧;
还有另外一个jar包,gnujaxp.jar,这个引入之后编译的时候会报错,应该是xsd校验的问题,索性直接去掉了,不影响实现。
2.具体实现:
public static void main(String [] args){
//数据源
String[] rk = getRowKeys(bid);
double[][]data = getData(bid,rk);
String[] colKeys = getColKey();
// 准备数据
CategoryDataset dataset = createDataset(rk, data,colKeys );
// 生成JFreeChart对象
JFreeChart freeChart = createChart(dataset);
// 输出图片到浏览器
response.setContentType("image/jpeg");
OutputStream ops = response.getOutputStream();
ChartUtilities.writeChartAsJPEG(ops, freeChart, 640, 480);
ops.close();
//保存图片到本地
saveAsFile(freeChart, "yourPath", 600, 400); }
private String[] getRowKeys(byte[] bid) throws PicException {
//实现
}
private double[][] getData(byte[] bid,String [] rk){
//实现
}
private String[] getColKey() {
//实现
}
public static CategoryDataset createDataset(String[] rowKeys, double[][] data,String[] colKeys) { return DatasetUtilities.createCategoryDataset(rowKeys, colKeys, data);
}
// 保存为文件
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, 600, 400);
// 保存为JPEG
ChartUtilities.writeChartAsJPEG(out, chart, 600, 400); out.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
// do nothing
}
}
}
}
// 根据CategoryDataset创建JFreeChart对象
public static JFreeChart createChart(CategoryDataset categoryDataset) {
// 创建JFreeChart对象:ChartFactory.createLineChart
JFreeChart jfreechart = ChartFactory.createLineChart("当年每月排放总量", // 标题
"月份", // categoryAxisLabel (category轴,横轴,X轴标签)
"数值", // valueAxisLabel(value轴,纵轴,Y轴的标签)
categoryDataset, // dataset
PlotOrientation.VERTICAL, true, // legend
false, // tooltips
false); // URLs
// 使用CategoryPlot设置各种参数。以下设置可以省略。
//设置字体解决乱码问题
CategoryPlot plot = (CategoryPlot) jfreechart.getPlot();
jfreechart.getTitle().setFont(new Font("微软雅黑", Font.BOLD, 18));
NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
rangeAxis.setLabelFont(new Font("微软雅黑", Font.BOLD, 18)); CategoryAxis domainAxis = plot.getDomainAxis();
domainAxis.setLabelFont(new Font("微软雅黑", Font.BOLD, 18)); // 背景色 透明度
plot.setBackgroundAlpha(0.5f);
// 前景色 透明度
plot.setForegroundAlpha(0.5f);
// 其他设置 参考 CategoryPlot类 return jfreechart;
}