导入jfreechart-1.0.2.zip\jfreechart-1.0.2\lib中的jcommon-1.0.5.jar与jfreechart-1.0.2.jar两个包
参照jfreechart目录中的 intro.htm 与 初用JFreechart报错!!!!!-木木论坛.htm 两个htm页面完成带百分比饼状和柱状图的生成
具体查看drp中ChartDemoServlet类,以下是简单示例代码:
/**
* 示例1:演示通过servlet直接输出图表
*/
public class ChartDemoServlet extends HttpServlet {
/**
* 设置图片
*/
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException
{
res.setContentType("image/jpeg");
DefaultPieDataset data = getDataSet();
JFreeChart chart = ChartFactory.createPie3DChart("水果产量图",
data,
true,
false,
false
);
ChartUtilities.writeChartAsJPEG(res.getOutputStream(),
100,chart,400,300,null);
}
/**
* 显示图片
*/
private static DefaultPieDataset getDataSet() {
DefaultPieDataset dataset = new DefaultPieDataset();
dataset.setValue("苹果",100);
dataset.setValue("梨子",200);
dataset.setValue("葡萄",300);
dataset.setValue("香蕉",400);
dataset.setValue("荔枝",500);
return dataset;
}
}
/*
**示例2:drp中具体示例
*/
public class ChartDemoServlet extends BaseServlet {
private StatReportManager statReportManager;
@Override
public void init() throws ServletException {
statReportManager = (StatReportManager)getBeanFactory().getServiceObject(StatReportManager.class);
}
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
res.setContentType("image/jpeg");
DefaultPieDataset data = getDataSet();
JFreeChart chart = ChartFactory.createPieChart3D("分销商等级分布图", data, true,false, false);
PiePlot3D plot=(PiePlot3D)chart.getPlot();
// 图片中显示百分比:默认方式
//plot.setLabelGenerator(new StandardPieSectionLabelGenerator(StandardPieToolTipGenerator.DEFAULT_TOOLTIP_FORMAT));
// 图片中显示百分比:自定义方式,{0} 表示选项, {1} 表示数值, {2} 表示所占比例 ,小数点后两位
plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0}={1}({2})", NumberFormat.getNumberInstance(), new DecimalFormat("0.00%")));
// 图例显示百分比:自定义方式, {0} 表示选项, {1} 表示数值, {2} 表示所占比例
plot.setLegendLabelGenerator(new StandardPieSectionLabelGenerator("{0}={1}({2})"));
ChartUtilities.writeChartAsJPEG(res.getOutputStream(),
1.0f, //数值越大图像越清晰
chart, 400,300, null);
}
/**
* 获取一个演示用的简单数据集对象
*
* @return
*/
private DefaultPieDataset getDataSet() {
DefaultPieDataset dataset = new DefaultPieDataset();
Map<String, Integer> map = statReportManager.getClientLevelCount();
for (Iterator<Map.Entry<String, Integer>> iter=map.entrySet().iterator(); iter.hasNext();) {
Map.Entry<String, Integer> entry = iter.next();
dataset.setValue(entry.getKey(), entry.getValue());
}
return dataset;
}
}