0.环境配置,添加Jar包并修改web.xml
1<servlet>
2 <servlet-name>DisplayChart</servlet-name>
3 <servlet-class>org.jfree.chart.servlet.DisplayChart</servlet-class>
4 </servlet>
5
6 <servlet-mapping>
7 <servlet-name>DisplayChart</servlet-name>
8 <url-pattern>/DisplayChart</url-pattern>
9 </servlet-mapping>
1.组装柱状图所需要的数据集
1DefaultCategoryDataset dataset = new DefaultCategoryDataset();
2dataset.addValue(柱状图长度,"", "柱体下方显示名称");
2.创建柱状图
1JFreeChart chart = ChartFactory.createBarChart3D("柱状图标题", "横轴标题", "纵轴标题",dataset, PlotOrientation.VERTICAL, false, false, false);
3.柱状图展现样式处理:
1CategoryPlot plot = chart.getCategoryPlot();
2 //设置网络背景颜色
3 plot.setBackgroundPaint(java.awt.Color.WHITE);
4 //设置网格竖线颜色
5 plot.setDomainGridlinePaint(java.awt.Color.pink);
6 //设置网格横线颜色
7 plot.setRangeGridlinePaint(java.awt.Color.pink);
8 BarRenderer3D renderer = new BarRenderer3D();
9 renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
10 renderer.setBaseItemLabelsVisible(true);
11 //设置柱宽度
12 renderer.setMaxBarWidth(0.04);
13 //设置数值显示字体及大小
14 renderer.setItemLabelFont(new java.awt.Font("黑体",java.awt.Font.PLAIN,10));
15 //设置正值柱图数值的显示位置
16 renderer.setPositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12,TextAnchor.BASELINE_LEFT));
17 //设置负值柱图数值的显示位置
18 renderer.setNegativeItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE7,TextAnchor.BASELINE_LEFT));
19 renderer.setItemLabelAnchorOffset(10D);
20 renderer.setItemLabelsVisible(true);
21 //设置柱的间距
22 renderer.setItemMargin(0);
23 plot.setRenderer(renderer);
24 plot.setDomainAxisLocation(AxisLocation.TOP_OR_LEFT);
25 plot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_LEFT);
26 org.jfree.chart.axis.CategoryAxis domainAxis = plot.getDomainAxis();
27 //domainAxis.setLowerMargin(0.1);//设置距离图片左端距离此时为10%
28 //domainAxis.setUpperMargin(0.1);//设置距离图片右端距离此时为百分之10
29 domainAxis.setCategoryLabelPositionOffset(10);//图表横轴与标签的距离(10像素)
30 domainAxis.setCategoryMargin(0.2);//横轴标签之间的距离20%
31 //domainAxis.setMaximumCategoryLabelLines(1);
32 //domainAxis.setMaximumCategoryLabelWidthRatio(0);
4.页面展现柱状图
I.JSP代码,将JFreeChart写入临时文件,用于页面展现
1String filename = ServletUtilities.saveChartAsPNG(chart, 700, 400, null, session);
2String graphURL = request.getContextPath() + "/DisplayChart?filename=" + filename;
II.页面展现
1<img src="<%=graphURL %>" width="700" height="400" border ="0" usemap = "#<%=filename%>">
若要简单实现功能,可以只做三个操作:添加jar包,修改web.xml,编写jsp文件(集合上述代码)