日期:2014-05-17  浏览次数:20705 次

jfreechart生成多张图表
jfreechart生成的图表总是被struts发往了另一个页面,
怎么在一张页面中 显示多张图表?

------解决方案--------------------
同时生产多个图表。生成的图表放到项目运行环境下的某个目录中。在jsp中用<img>标签使用图片相对地址把图片显示不就可以了。实例代码:
/**
* 饼图生成 
* @param title 图表标题 
* @param w 图表宽度
* @param h 图表高度
* @return path 图表地址 
* @throws Exception 
*/
@SuppressWarnings("unchecked")
public String generatePieChart(
String title, 
int w, 
int h,
String flag) throws Exception{
FileOutputStream fos = null; 
String filename = "";//生成图片相对地址 
try {
PieDataset dataset = getDataSetForPie(flag);//数据源 
JFreeChart chart = ChartFactory.createPieChart3D(
title, //图表标题 
dataset, //数据集 
true, //是否显示图例(对于简单的柱状图必须是false) 
false, //是否生成工具 
false //是否生成URL链接 
);
String path = getSystemPath("/download");//图片保存绝对地址 
String systime = getSystemTime();//取得系统时间 
File file = new File(path);
if(!file.isDirectory()) {//文件路径不存在场合 
file.mkdirs();
}
fos = new FileOutputStream(path +"/"+ systime + ".jpeg"); 
//JFreeChart相关设置 
chart.getTitle().setFont(new Font("simsun", Font.PLAIN, 16));//标题字体设置 
chart.getLegend().setItemFont(new Font("simsun", Font.PLAIN, 16));//底部字体设置 
PiePlot pp = (PiePlot)chart.getPlot();
pp.setLabelFont(new Font("simsun", Font.PLAIN, 14));//饼图内容字体设置
pp.setLabelGenerator(new org.jfree.chart.labels
.StandardPieSectionLabelGenerator("{0}:{2}"));//显示饼图内容、百分比 0:内容;2:百分比 
pp.setStartAngle(290D);
pp.setDirection(Rotation.CLOCKWISE);
//pp.setForegroundAlpha(0.5F);
//保存为jpeg格式图片 
ChartUtilities.writeChartAsJPEG(fos, 1, chart, w, h , null);
fos.flush();
fos.close();
filename = "download/" + systime + ".jpeg";//相对地址 
} catch (IOException e) {
throw e;
}catch (InterruptedException e) {
throw e;
} catch (Exception e) {
throw e;
}finally{
if(fos != null) {
try {//资源关闭 
fos.flush();
fos.close();
} catch (IOException e) {
throw e;
}
}
}
return filename;
}
 /**
* 取得系统绝对地址
* @param flag
* @return path 
*/
public String getSystemPath(String flag) {
String path = ServletActionContext.getServletContext().getRealPath(flag);
return path;
}

/**
* 取得系统当前时间 格式:yyyyMMddHHmmssSSS 
* @return str 
* @throws InterruptedException 
*/
@SuppressWarnings("static-access")
public String getSystemTime() throws InterruptedException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS", 
Locale.CHINA);
String str = sdf.format(new Date());
try {
Thread.currentThread().sleep(10);
} catch (InterruptedException e) {
throw e;
}
return str;
}