JFREECHART是java的一种出图库,已经能解决当前大部分的出图需求,本文详解如何架构一个良好的框架。能力有限,不详忘谅。
由于时间紧急,而且又是一期,没敢处理太多的口径,只为有一个良好的出图架构,以方便2期开发方便,需求不明确,也就随便获取了一些口径。
出图须知:
首先,我们按照不同口径获取不同图的生产方法;
然后,需要知道不同口径获取数据的方法;
这两点我写在了一个Action里面,代码如下:
package com.bdqn.action;
import java.util.LinkedList;
import java.util.List;
import org.jfree.chart.JFreeChart;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.general.DatasetUtilities;
import org.jfree.data.general.DefaultPieDataset;
import com.bdqn.entity.ChartParams;
import com.bdqn.manager.JfreeChartManageDomain;
import com.bdqn.service.MovieInfomationService;
import com.bdqn.util.ActionUtil;
import com.bdqn.util.JFreeChartUtil;
import com.opensymphony.xwork2.Preparable;
/*
* @author mr.xiao
*/
public class JFreechartAction extends BaseAction implements Preparable {
private static final long serialVersionUID = -7719073394011378575L;
public JfreeChartManageDomain getchartService() {
return (JfreeChartManageDomain) getBean("chartdomain");
}
public String returnString;
public String getReturnString() {
return returnString;
}
public void setReturnString(String returnString) {
this.returnString = returnString;
}
/**
* @deprecated
* @return
*/
public MovieInfomationService getMovieInfomationService() {
return (MovieInfomationService) getBean("movieinfomationService");
}
// 封装了chart参数的entity
public ChartParams chartparams;
public ChartParams getChartparams() {
return chartparams;
}
public void setChartparams(ChartParams chartparams) {
this.chartparams = chartparams;
}
// 用来接收生成后的chart
public JFreeChart chart;
public JFreeChart getChart() {
return chart;
}
public void setChart(JFreeChart chart) {
this.chart = chart;
}
public String chooseParams() {
// 这只是一个权限
return "chooseParams";
}
public String chartshow() {
// chartparams=this.chartparams;
return "chartshow";
}
/**
* @author 肖杨\OGDEN
* @effect 处理chart的Action
* @return actionForwordString OR null
*/
@SuppressWarnings("unchecked")
public String createChart() {
String title = "";// 初始化标题
List list = null;
List tabletitle = null;
try {
/*
* 按照类型来获取数据
*/
if (chartparams.getBigboss().equalsIgnoreCase("yplx")) {
list = this.getYPLXData(chartparams);
if (list.isEmpty()) {
this.setReturnString("该配置类型数据为空!!");
return "HAVEINFO";
}
// 若是表格 直接先生成表格
if (chartparams.getChartType().equalsIgnoreCase("table")) {
tabletitle = getTableTitle();// 得到表头
return willTable(list, tabletitle, chartparams);
}
title = "影片类型";
} else if (chartparams.getBigboss().equalsIgnoreCase("lxsc")) {// 工作量
list = this.getLXSCData(chartparams);
if (list.isEmpty()) {
this.setReturnString("该配置类型时长数据为空!!");
return "HAVEINFO";
}
// 若是表格 直接先生成表格
if (chartparams.getChartType().equalsIgnoreCase("table")) {
tabletitle = getTableTitle();// 得到表头
return willTable(list, tabletitle, chartparams);
}
title = "编目进度";
} else if (chartparams.getBigboss().equalsIgnoreCase("gzl")) {// 工作量
list = this.getGZLData(chartparams);
if (list.isEmpty()) {
this.setReturnString("该配置工作量数据为空!!");
return "HAVEINFO";
}
// 若是表格 直接先生成表格
if (chartparams.getChartType().equalsIgnoreCase("table")) {
tabletitle = getTableTitle();// 得到表头
return willTable(list, tabletitle, chartparams);
}
title = "编目进度";
} else if (chartparams.getBigboss().equalsIgnoreCase("bmjd")) {
list = this.getBMJDData(chartparams);
if (list.isEmpty()) {
this.setReturnString("该配置编目进度数据为空!!");
return "HAVEINFO";
}
// 若是表格 直接先生成表格
if (chartparams.getChartType().equalsIgnoreCase("table")) {
tabletitle = getTableTitle();// 得到表头
return willTable(list, tabletitle, chartparams);
}
title = "编目进度";
}
} catch (Exception e) {
this.setReturnString("获取数据出错");
e.printStackTrace();
return "HAVEINFO";
}
/*
* 按照不同图形来生成报表
*/
if (chartparams.getChartType().equalsIgnoreCase("pie")) {// 饼图
this.setChart(JFreeChartUtil.createPieChart(
(DefaultPieDataset) list.get(0), title, true));
return SUCCESS;
} else if (chartparams.getChartType().equalsIgnoreCase("bar")) {// 棒子图
this.setChart(JFreeChartUtil.createBarChart((CategoryDataset) list
.get(0), title, list.get(1).toString(), list.get(2)
.toString(), true));
return SUCCESS;
} else if (chartparams.getChartType().equalsIgnoreCase("foldline")) {// 折线
this.setChart(JFreeChartUtil.createFoldLineChar(title, list.get(1)
.toString(), list.get(2).toString(), (CategoryDataset) list
.get(0), ""));
return SUCCESS;
} else {
this.setReturnString("解析报表错误");
return "HAVEINFO";
}
}
/**
* @effect 生成表头
* @return 表头字符串list OR null
*/
public List<String> getTableTitle() {
List<String> list = new LinkedList<String>();
if (chartparams.getBigboss().equalsIgnoreCase("yplx")) {
list.add("类型名称");
list.add("影片数量");
} else if (chartparams.getBigboss().equalsIgnoreCase("gzl")) {
list.add("编目人员");
list.add("数量");
} else if (chartparams.getBigboss().equalsIgnoreCase("bmjd")) {
list.add("编目状态");
list.add("影片数量");
} else if (chartparams.getBigboss().equalsIgnoreCase("lxsc")) {
list.add("类型名称");
list.add("影片时长");
}
return list;
}
/**
* @effect 若是table得到参数返回table列表页面,此方法为复用剥离出action
* @param list
* @param chartparams
* @return ActionString
*/
public String willTable(List list, List tableTitle, ChartParams chartparams) {
new ActionUtil().getRequest().setAttribute("list", list);// 获取表格信息
new ActionUtil().getRequest().setAttribute("tabletitles", tableTitle);// 获取表头信息
new ActionUtil().getRequest().setAttribute("chartparams", chartparams);// 获取参数集合
return "createtable";
}
/**
* @author 肖杨\OGDEN
* @category DATA
* @param chartType
* 影片类型
* @return List :chartType为pie,list封转一个值,键值对应好的DefaultPieDataset
* chartType为bar,foldline封装三个值,CategoryDataset、X轴名称、Y轴名称。 \null
* @effect 获取影片类型数据并封装进一个list里
* @throws Exception
*/
@SuppressWarnings("unchecked")
private List getYPLXData(ChartParams chartparams) throws Exception {// 影片类型
List returnList = new LinkedList();
// List bigBossAndParamList = getBigBossAndparamList(chartparams);
List<Object[]> list = this.getchartService().getYPLXList(chartparams);
// List<Object[]> list = this.getMovieInfomationService()
// .getChartNameAndValueList((Integer) bigBossAndParamList.get(0),
// (List) bigBossAndParamList.get(1));
if (chartparams.getChartType().equalsIgnoreCase("table")) {
return list;
} else if (chartparams.getChartType().equalsIgnoreCase("pie")) {// 饼图
DefaultPieDataset dpdDataset = new DefaultPieDataset();
for (Object[] ob : list) {
dpdDataset.setValue(ob[0].toString(), Integer.parseInt(ob[1]
.toString()));
}
returnList.add(dpdDataset);
} else if (chartparams.getChartType().equalsIgnoreCase("bar")
|| chartparams.getChartType().equalsIgnoreCase("foldline")) {// 棒子图
String[] columnKeys = new String[list.size()];
String[] datas = new String[list.size()];
for (int i = 0; i < list.size(); i++) {
Object[] temp = list.get(i);
datas[i] = temp[1].toString();
columnKeys[i] = temp[0].toString();
}
double[][] data = new double[][] { this.stringToDouble(datas) };
CategoryDataset dataset = DatasetUtilities.createCategoryDataset(
new String[] { "影片" }, columnKeys, data);
returnList.add(dataset);
returnList.add("类型");// X轴
returnList.add("数量");// Y轴
}
return returnList;
}
/**
* @author 肖杨\OGDEN
* @category DATA
* @param chartType
* 类型时长
* @return List :chartType为pie,list封转一个值,键值对应好的DefaultPieDataset
* chartType为bar,foldline封装三个值,CategoryDataset、X轴名称、Y轴名称。 \null
* @effect 获取影片类型与时长数据并封装进一个list里
* @throws Exception
*/
@SuppressWarnings("unchecked")
private List getLXSCData(ChartParams chartparams) throws Exception {// 类型时长
List returnList = new LinkedList();
// List bigBossAndParamList = getBigBossAndparamList(chartparams);
List<Object[]> list = this.getchartService().getLXSCList(chartparams);
// List<Object[]> list = this.getMovieInfomationService()
// .getChartNameAndValueList((Integer) bigBossAndParamList.get(0),
// (List) bigBossAndParamList.get(1));
if (chartparams.getChartType().equalsIgnoreCase("table")) {
return list;
} else if (chartparams.getChartType().equalsIgnoreCase("pie")) {// 饼图
DefaultPieDataset dpdDataset = new DefaultPieDataset();
for (Object[] ob : list) {
dpdDataset.setValue(ob[0].toString(), Integer.parseInt(this
.dwPor(ob[1].toString(),chartparams)));
}
returnList.add(dpdDataset);
} else if (chartparams.getChartType().equalsIgnoreCase("bar")
|| chartparams.getChartType().equalsIgnoreCase("foldline")) {// 棒子图
String[] columnKeys = new String[list.size()];
String[] datas = new String[list.size()];
for (int i = 0; i < list.size(); i++) {
Object[] temp = list.get(i);
datas[i] =this
.dwPor(temp[1].toString(),chartparams);
columnKeys[i] = temp[0].toString();
}
double[][] data = new double[][] { this.stringToDouble(datas) };
CategoryDataset dataset = DatasetUtilities.createCategoryDataset(
new String[] { "类型" }, columnKeys, data);
returnList.add(dataset);
returnList.add("类型");// X轴
returnList.add("时长");// Y轴
}
return returnList;
}
/**
* 将hh:mm:ss.ff统计
*/
private String dwPor(String sixtime,ChartParams chartparams) {
String qian[];// 0时 1分 2秒
String hou = "";
int value=0;
qian = sixtime.substring(0, sixtime.indexOf(".")).split(":");
hou = sixtime.substring(sixtime.indexOf(".") + 1, sixtime.length());
if (chartparams.getScdw().equalsIgnoreCase("zhen")) {
value = ((Integer.parseInt(qian[0]) * 60) * 60) * 24
+ (Integer.parseInt(qian[1]) * 60) * 24
+ Integer.parseInt(qian[2]) * 24 + Integer.parseInt(hou);
} else if (chartparams.getScdw().equalsIgnoreCase("se")) {
value = ((Integer.parseInt(qian[0]) * 60) * 60)
+ (Integer.parseInt(qian[1]) * 60) + Integer.parseInt(qian[2])
+ Integer.parseInt(hou) / 24;
} else if (chartparams.getScdw().equalsIgnoreCase("mu")) {
value = (Integer.parseInt(qian[0]) * 60) + (Integer.parseInt(qian[1]))
+ (Integer.parseInt(qian[2]) / 60)
+ ((Integer.parseInt(hou) / 60) / 24);
} else if (chartparams.getScdw().equalsIgnoreCase("hour")) {
value = (Integer.parseInt(qian[0])) + (Integer.parseInt(qian[1]) / 60)
+ Integer.parseInt(qian[2]) / 60 / 60 + Integer.parseInt(hou)
/ 60 / 60 / 24;
}
return String.valueOf(value);
}
/**
* @author 肖杨\OGDEN
* @category DATA
* @param chartType
* 工作量
* @return List :chartType为pie,list封转一个值,键值对应好的DefaultPieDataset
* chartType为bar,foldline封装三个值,CategoryDataset、X轴名称、Y轴名称。 \null
* @effect 获取工作量数据并封装进一个list里
* @throws Exception
*/
@SuppressWarnings("unchecked")
private List getGZLData(ChartParams chartparams) throws Exception {// 工作量
List returnList = new LinkedList();
// List bigBossAndParamList = getBigBossAndparamList(chartparams);
List<Object[]> list = this.getchartService().getGZLList(chartparams);
// List<Object[]> list = this.getMovieInfomationService()
// .getChartNameAndValueList((Integer) bigBossAndParamList.get(0),
// (List) bigBossAndParamList.get(1));
if (chartparams.getChartType().equalsIgnoreCase("table")) {
return list;
} else if (chartparams.getChartType().equalsIgnoreCase("pie")) {// 饼图
DefaultPieDataset dpdDataset = new DefaultPieDataset();
for (Object[] ob : list) {
dpdDataset.setValue(ob[0].toString(), Integer.parseInt(ob[1]
.toString()));
}
returnList.add(dpdDataset);
} else if (chartparams.getChartType().equalsIgnoreCase("bar")
|| chartparams.getChartType().equalsIgnoreCase("foldline")) {// 棒子图
String[] columnKeys = new String[list.size()];
String[] datas = new String[list.size()];
for (int i = 0; i < list.size(); i++) {
Object[] temp = list.get(i);
datas[i] = temp[1].toString();
columnKeys[i] = temp[0].toString();
}
double[][] data = new double[][] { this.stringToDouble(datas) };
CategoryDataset dataset = DatasetUtilities.createCategoryDataset(
new String[] { "状态" }, columnKeys, data);
returnList.add(dataset);
returnList.add("种类");// X轴
returnList.add("数量");// Y轴
}
return returnList;
}
/**
* @author 肖杨\OGDEN
* @category DATA
* @param chartType
* 编目进度
* @return List :chartType为pie,list封转一个值,键值对应好的DefaultPieDataset
* chartType为bar,foldline封装三个值,CategoryDataset、X轴名称、Y轴名称。 \null
* @effect 获取编目进度数据并封装进一个list里
* @throws Exception
*/
@SuppressWarnings("unchecked")
private List getBMJDData(ChartParams chartparams) throws Exception {// 编目进度
List returnList = new LinkedList();
// List bigBossAndParamList = getBigBossAndparamList(chartparams);
List<Object[]> list = this.getchartService().getBMJDList(chartparams);
// List<Object[]> list = this.getMovieInfomationService()
// .getChartNameAndValueList((Integer) bigBossAndParamList.get(0),
// (List) bigBossAndParamList.get(1));
if (chartparams.getChartType().equalsIgnoreCase("table")) {
return list;
} else if (chartparams.getChartType().equalsIgnoreCase("pie")) {// 饼图
DefaultPieDataset dpdDataset = new DefaultPieDataset();
for (Object[] ob : list) {
dpdDataset.setValue(ob[0].toString(), Integer.parseInt(ob[1]
.toString()));
}
returnList.add(dpdDataset);
} else if (chartparams.getChartType().equalsIgnoreCase("bar")
|| chartparams.getChartType().equalsIgnoreCase("foldline")) {// 棒子图
String[] columnKeys = new String[list.size()];
String[] datas = new String[list.size()];
for (int i = 0; i < list.size(); i++) {
Object[] temp = list.get(i);
datas[i] = temp[1].toString();
columnKeys[i] = temp[0].toString();
}
double[][] data = new double[][] { this.stringToDouble(datas) };
CategoryDataset dataset = DatasetUtilities.createCategoryDataset(
new String[] { "进度" }, columnKeys, data);
returnList.add(dataset);
returnList.add("种类");// X轴
returnList.add("数量");// Y轴
}
return returnList;
}
/**
* @author 肖杨\OGDEN
* @category UTIL
* @param String数组
* @return double数组、
* @effect 将字符串数组转换成double数组
* @throws Exception
* 转换失败时
*/
public double[] stringToDouble(String[] temp) throws Exception {
double[] doubles = new double[temp.length];
for (int i = 0; i < temp.length; i++) {
doubles[i] = Double.valueOf(temp[i]);
}
return doubles;
}
/**
* @author 肖杨\OGDEN
* @return BigBoss(大类等级), paramList:1 起始时间 2 结束时间
* @deprecated 多余的解决方法
*/
@SuppressWarnings("unchecked")
private List getBigBossAndparamList(ChartParams chartparams) {
List list = new LinkedList();
List params = new LinkedList();
if (chartparams.getBigboss().equalsIgnoreCase("yplx")) {
list.add(1);// 大类返回1
// 添加参数集合
params.add(chartparams.getInterTime());
params.add(chartparams.getEndTime());
list.add(params);
}
return list;
}
public void prepare() throws Exception {
clearErrorsAndMessages();
}
}
另外,还需要用于不同图类美化的公用方法;
package com.bdqn.util;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.RenderingHints;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.AxisLocation;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.labels.ItemLabelAnchor;
import org.jfree.chart.labels.ItemLabelPosition;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.labels.StandardPieToolTipGenerator;
import org.jfree.chart.labels.StandardXYItemLabelGenerator;
import org.jfree.chart.labels.StandardXYToolTipGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.IntervalMarker;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.BarRenderer3D;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.chart.servlet.ServletUtilities;
import org.jfree.chart.title.LegendTitle;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.ui.Layer;
import org.jfree.ui.TextAnchor;
import org.jfree.util.Rotation;
/**
*
* <p>
* Title:根据数据集生成曲线图,饼图,柱状图,甘特图等
* </p>
*/
public class JFreeChartUtil {
/**
*
* 柱状图(一维,二维关系)
*
* @param title
*
* @param categoryAxisLabel
*
* @param valueAxisLabel
*
* @param dataset
*
* @return public static JFreeChart createHistogram(String title,
*
* String categoryAxisLabel, String valueAxisLabel,
*
* CategoryDataset dataset) {
*
* // ChartFactory工厂类
*
* JFreeChart chart = ChartFactory.createBarChart3D(title,
*
* categoryAxisLabel, valueAxisLabel, dataset,
*
* PlotOrientation.VERTICAL, true, false, false);
*
* // PlotOrientation.VERTICAL:让平行柱垂直显示 PlotOrientation.HORIZONTAL
* // 则让平行柱水平显示。
*
* // 字体由模糊变清晰
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
* chart.getRenderingHints().put(RenderingHints.KEY_TEXT_ANTIALIASING
* ,
*
* RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
*
* chart.setBackgroundPaint(Color.WHITE);
*
* CategoryPlot plot = chart.getCategoryPlot();
*
* CategoryAxis domainAxis = plot.getDomainAxis();
*
* // domainAxis.setVerticalCategoryLabels(false);
*
* domainAxis.setVisible(true);
*
* plot.setDomainAxis(domainAxis);
*
* // plot图形设计:绘图集plot对象
*
* ValueAxis rangeAxis = plot.getRangeAxis();
*
* // 设置最高的一个 Item 与图片顶端的距离
*
* rangeAxis.setUpperMargin(0.15);
*
* // 设置最低的一个Item 与图片底端的距离
*
* rangeAxis.setLowerMargin(0.15);
*
* // rangeAxis.set
*
* plot.setRangeAxis(rangeAxis);
*
* BarRenderer3D renderer = new BarRenderer3D();
*
* // render 绘制工具
*
* renderer.setBaseOutlinePaint(Color.BLACK);
*
* // 设置 Wall 的颜色
*
* renderer.setWallPaint(Color.gray);
*
* // 设置每种类型代表的柱的颜色
*
* renderer.setSeriesPaint(0, Color.YELLOW);
*
* renderer.setSeriesPaint(1, Color.GREEN);
*
* renderer.setSeriesPaint(2, Color.RED);
*
* renderer.setSeriesPaint(3, Color.CYAN);
*
* renderer.setSeriesPaint(5, Color.ORANGE);
*
* renderer.setSeriesPaint(4, Color.MAGENTA);
*
* renderer.setSeriesPaint(6, Color.DARK_GRAY);
*
* renderer.setSeriesPaint(7, Color.PINK);
*
* renderer.setSeriesPaint(8, Color.black);
*
* renderer.setSeriesPaint(9, new Color(0, 100, 255));
*
* renderer.setSeriesPaint(10, new Color(0, 0, 255));
*
* // 设置每个地区所包含的平行柱的之间距离
*
* renderer.setItemMargin(0.25);// 为25%
*
* // 显示每个柱的数值,并修改该数值的字体属性 // renderer.setItemLabelGenerator(new
* CategoryItemLabelGenerator()); //
* renderer.setItemLabelGenerator(new //
* StandardCategoryItemLabelGenerator()); //
* renderer.setItemLabelsVisible(true);
*
* // plot.setRenderer(renderer);
*
* // 设置柱的透明度
*
* plot.setForegroundAlpha(0.6f);
*
* // 设置地区、收入的显示位置
*
* plot.setDomainAxisLocation(AxisLocation.TOP_OR_RIGHT);
*
* plot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_RIGHT);
*
* //----------设置标题字体--------------------------
*
* ValueAxis rAxis = plot.getRangeAxis();
*
* TextTitle textTitle = chart.getTitle();
*
* textTitle.setFont(new Font("黑体", Font.PLAIN, 20));
*
* //*------设置X轴坐标上的文字-----------
*
* domainAxis.setTickLabelFont(new Font("sans-serif", Font.PLAIN,
* 15));
*
* //*------设置X轴的标题文字------------
*
* domainAxis.setLabelFont(new Font("宋体", Font.PLAIN, 15));
*
* //*------设置Y轴坐标上的文字-----------
*
* rAxis.setTickLabelFont(new Font("sans-serif", Font.PLAIN, 15));
*
* //*------设置Y轴的标题文字------------
*
* rAxis.setLabelFont(new Font("黑体", Font.PLAIN, 15));
*
* //*---------设置柱状体上的显示的字体---------
*
* // renderer.setItemLabelGenerator(new LabelGenerator(0.0));
* renderer.setItemLabelFont(new Font("宋体", Font.PLAIN, 12));
*
* renderer.setItemLabelsVisible(true);
*
* return chart;
*
* }
*/
/**
*
* 创建饼图
*
* @param dataset
*
* @param title
*
* @return public static JFreeChart createPieChart(String title,
*
* DefaultPieDataset dataset) {
*
* // ChartFactory工厂类
*
* JFreeChart chart = ChartFactory.createPieChart3D(title, dataset,
* true,
*
* true, true);
*
* // 设定饼图标题
*
* chart.setTitle(new TextTitle(title, new Font("黑体", Font.ITALIC,
* 15)));
*
* // 定制子标题
*
* // chart.addSubtitle(new TextTitle("2005质量技术监督局财务分析", new
* Font("隶书", // Font.ITALIC, 12)));
*
* // 设定背景
*
* chart.setBackgroundPaint(Color.white);
*
* // 饼图使用一个PiePlot
*
* PiePlot pie = (PiePlot) chart.getPlot();
*
* // 设定显示格式(名称加百分比或数值)
*
* // pie.setPercentFormatString("#,###0.0#%");
*
* // 设定百分比显示格式
*
* pie.setBackgroundPaint(Color.white);
*
* // pie.setSectionLabelFont(new Font("黑体", Font.TRUETYPE_FONT,
* 12));
*
* // 设定背景透明度(0-1.0之间)
*
* pie.setBackgroundAlpha(0.6f);
*
* // 设定前景透明度(0-1.0之间)
*
* pie.setForegroundAlpha(0.90f);
*
* return chart;
*
* }
*/
/**
*
* 创建曲线图
*
* @param title
*
* @param subtitleStr
*
* @param domain
*
* @param range
*
* @param dataset
*
* @return public static JFreeChart JFreeChartSeriesChart(String title,
*
* String subtitleStr, String domain, String range,
*
* TimeSeriesCollection dataset) { // 时间曲线元素
*
* JFreeChart chart = ChartFactory.createTimeSeriesChart(title,
* domain,
*
* range, dataset, true, true, false);
*
* TextTitle subtitle = new TextTitle(subtitleStr, new Font("黑体",
*
* Font.BOLD, 12));
*
* chart.addSubtitle(subtitle);
*
* chart.setTitle(new TextTitle(title, new Font("隶书", Font.ITALIC,
* 15)));
*
* chart.setBackgroundPaint(new GradientPaint(0, 0, Color.white, 0,
* 1000,
*
* Color.blue));
*
* return chart;
*
* }
*/
/**
*
* 取得session中图像的地址
*
* @param chart
*
* @param session
*
* @param request
*
* @return
*
* @throws IOException
* public static String getGraphURL(JFreeChart chart,
* HttpSession session,
*
* HttpServletRequest request, int width, int height)
*
* throws IOException {
*
* String filename = ServletUtilities.saveChartAsPNG(chart,
* width, height,
*
* null, session);
*
* String graphURL = request.getContextPath()
*
* + "/servlet/DisplayChart?filename=" + filename;
*
* return graphURL;
*
* }
* */
/**
* <br>
* 方法名称:createPieChart <br>
* 功能描述:创建PieChart(饼图)图表 <br>
* 返 回 值:JFreeChart <br>
* 创 建 人: <br>
* 创建日期:Mar 30, 2010 12:59:07 PM
*
* @param dataset
*/
public static JFreeChart createPieChart(DefaultPieDataset dataset,
String title, boolean is3D) {
JFreeChart chart = null;
if (is3D) {
chart = ChartFactory.createPieChart3D(title, // 图表标题
dataset, // 数据集
true, // 是否显示图例
true, // 是否显示工具提示
true // 是否生成URL
);
} else {
chart = ChartFactory.createPieChart(title, // 图表标题
dataset, // 数据集
true, // 是否显示图例
true, // 是否显示工具提示
true // 是否生成URL
);
}
// 设置标题字体,为了防止中文乱码:必须设置字体
chart.setTitle(new TextTitle(title, new Font("黑体", Font.ITALIC, 22)));
// 设置图例的字体,为了防止中文乱码:必须设置字体
chart.getLegend().setItemFont(new Font("黑体", Font.PLAIN, 12));
// 获取饼图的Plot对象(实际图表)
PiePlot plot = (PiePlot) chart.getPlot();
// 图形边框颜色
plot.setBaseSectionOutlinePaint(Color.GRAY);
// 图形边框粗细
plot.setBaseSectionOutlineStroke(new BasicStroke(0.0f));
// 设置饼状图的绘制方向,可以按顺时针方向绘制,也可以按逆时针方向绘制
plot.setDirection(Rotation.ANTICLOCKWISE);
// 设置绘制角度(图形旋转角度)
plot.setStartAngle(70);
// 设置突出显示的数据块
// plot.setExplodePercent("One", 0.1D);
// 设置背景色透明度
plot.setBackgroundAlpha(0.7F);
// 设置前景色透明度
plot.setForegroundAlpha(0.65F);
// 设置区块标签的字体==为了防止中文乱码:必须设置字体
plot.setLabelFont(new Font("宋体", Font.PLAIN, 12));
// 扇区分离显示,对3D图不起效
if (is3D)
plot.setExplodePercent(
dataset.getKey(dataset.getKeys().size() - 1), 0.1D);
// 图例显示百分比:自定义方式,{0} 表示选项, {1} 表示数值, {2} 表示所占比例 ,小数点后两位
plot.setLabelGenerator(new StandardPieSectionLabelGenerator(
"{0}:{1}\r\n({2})", NumberFormat.getNumberInstance(),
new DecimalFormat("0.00%")));
// 指定显示的饼图为:圆形(true) 还是椭圆形(false)
plot.setCircular(true);
// 没有数据的时候显示的内容
plot.setNoDataMessage("找不到可用数据");
// 设置鼠标悬停提示
plot.setToolTipGenerator(new StandardPieToolTipGenerator());
// 设置热点链接
// plot.setURLGenerator(new StandardPieURLGenerator("detail.jsp"));
return chart;
}
/**
*<br>
* 方法名称:createPieChart <br>
* 功能描述:创建BarChart(柱状图/条形图)图表 <br>
* 返 回 值:JFreeChart <br>
* 创 建 人: <br>
* 创建日期:Mar 30, 2010 12:59:07 PM
*
* @param dataset
*/
@SuppressWarnings("deprecation")
public static JFreeChart createBarChart(CategoryDataset dataset,
String title, String x, String y, boolean is3D) {
JFreeChart chart = null;
BarRenderer renderer = null;
if (is3D) {
chart = ChartFactory.createBarChart3D( // 3D柱状图
// JFreeChart chart = ChartFactory.createLineChart3D(
// //3D折线图
title, // 图表的标题
x, // 目录轴的显示标签
y, // 数值轴的显示标签
dataset, // 数据集
PlotOrientation.VERTICAL, // 图表方式:V垂直;H水平
true, // 是否显示图例
false, // 是否显示工具提示
false // 是否生成URL
);
// 解决X轴字数过长出现省略号的问题
CategoryPlot plot = chart.getCategoryPlot();
CategoryAxis domainAxis = plot.getDomainAxis();
domainAxis.setMaximumCategoryLabelLines(10);// 行数,根据需要自己设
domainAxis.setMaximumCategoryLabelWidthRatio(1);// 每行宽度,这里设一个汉字宽
// 柱图的呈现器
renderer = new BarRenderer3D();
renderer
.setItemLabelGenerator(new StandardCategoryItemLabelGenerator());
renderer.setItemLabelFont(new Font("黑体", Font.PLAIN, 12));
renderer.setItemLabelsVisible(true);
// 3D柱子上不能正常显示数字
// 注意:如果数值太大切前面的柱子低于后面的柱子,那么前面的那个数值将被挡住,所以将下面方法中的0该为-值
ItemLabelPosition itemLabelPositionFallback = new ItemLabelPosition(
ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT,
TextAnchor.HALF_ASCENT_LEFT, -1.3D);
// 设置不能正常显示的柱子label的position
renderer
.setPositiveItemLabelPositionFallback(itemLabelPositionFallback);
renderer
.setNegativeItemLabelPositionFallback(itemLabelPositionFallback);
} else {
chart = ChartFactory.createBarChart( // 柱状图
// JFreeChart chart = ChartFactory.createLineChart3D(
// //3D折线图
title, // 图表的标题
x, // 目录轴的显示标签
y, // 数值轴的显示标签
dataset, // 数据集
PlotOrientation.VERTICAL, // 图表方式:V垂直;H水平
true, // 是否显示图例
false, // 是否显示工具提示
false // 是否生成URL
);
// 解决X轴字数过长出现省略号的问题
CategoryPlot plot = chart.getCategoryPlot();
CategoryAxis domainAxis = plot.getDomainAxis();
domainAxis.setMaximumCategoryLabelLines(10);// 行数,根据需要自己设
domainAxis.setMaximumCategoryLabelWidthRatio(0.2f);// 每行宽度,这里设一个汉字宽
// 柱图的呈现器
renderer = new BarRenderer();
renderer.setIncludeBaseInRange(true); // 显示每个柱的数值,并修改该数值的字体属性
renderer
.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
renderer.setBaseItemLabelsVisible(true);
}
// 设置图片背景
// chart.setBackgroundPaint(Color.PINK);
// 为了防止中文乱码:必须设置字体
chart.setTitle(new TextTitle(title, new Font("黑体", Font.PLAIN, 22)));
LegendTitle legend = chart.getLegend(); // 获取图例
legend.setItemFont(new Font("宋体", Font.PLAIN, 12)); // 设置图例的字体,防止中文乱码
CategoryPlot plot = (CategoryPlot) chart.getPlot(); // 获取柱图的Plot对象(实际图表)
// 设置柱图背景色(注意,系统取色的时候要使用16位的模式来查看颜色编码,这样比较准确)
plot.setBackgroundPaint(new Color(255, 255, 204));
plot.setForegroundAlpha(0.65F); // 设置前景色透明度
// 设置横虚线可见
plot.setRangeGridlinesVisible(true);
// 虚线色彩
plot.setRangeGridlinePaint(Color.gray);
ValueAxis rangeAxis = plot.getRangeAxis();
// 设置最高的一个Item与图片顶端的距离
rangeAxis.setUpperMargin(0.2);
// 设置最低的一个Item与图片底端的距离
rangeAxis.setLowerMargin(0.3);
CategoryAxis domainAxis = plot.getDomainAxis(); // 获取x轴
domainAxis.setMaximumCategoryLabelWidthRatio(1.0f);// 横轴上的 Lable 是否完整显示
domainAxis.setLabelFont(new Font("宋体", Font.TRUETYPE_FONT, 14));// 设置字体,防止中文乱码
domainAxis.setTickLabelFont(new Font("宋体", Font.PLAIN, 12));// 轴数值
// h.setCategoryLabelPositions(CategoryLabelPositions.UP_45);//45度倾斜
plot.getRangeAxis().setLabelFont(new Font("宋体", Font.PLAIN, 14)); // Y轴设置字体,防止中文乱码
renderer.setBaseOutlinePaint(Color.BLACK); // 设置柱子边框颜色
renderer.setDrawBarOutline(true); // 设置柱子边框可见
renderer.setSeriesPaint(0, Color.YELLOW); // 设置每个柱的颜色
renderer.setSeriesPaint(1, Color.green);
renderer.setSeriesPaint(2, Color.RED);
renderer.setSeriesPaint(3, Color.CYAN);
renderer.setSeriesPaint(5, Color.ORANGE);
renderer.setSeriesPaint(4, Color.MAGENTA);
renderer.setSeriesPaint(6, Color.DARK_GRAY);
renderer.setSeriesPaint(7, Color.PINK);
renderer.setSeriesPaint(8, Color.black);
renderer.setItemMargin(0.1); // 设置每个地区所包含的平行柱的之间距离
plot.setRenderer(renderer); // 给柱图添加呈现器
plot.setForegroundAlpha(0.7f); // 设置柱的透明度
// renderer.setMaximumBarWidth(0.2); // 设置柱子宽度
// renderer.setMinimumBarLength(0.6); // 设置柱子高度
// 设置横坐标显示位置(默认是下方);
// plot.setDomainAxisLocation(AxisLocation.TOP_OR_RIGHT);
// 设置纵坐标显示位置(默认是左方)
// plot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_RIGHT);
// 没有数据的时候显示的内容
plot.setNoDataMessage("找不到可用数据");
return chart;
}
/**
*<br>
* 方法名称:JFreeChartSeriesChart <br>
* 功能描述:创建曲线图 <br>
* 注意事项:一般曲线图不用加域所以后4个参数一般为(false,null,0,0) <br>
* 参 数:title-标题;subtitleStr-子标题;domain-x轴标志;range-y轴标志;dataset-设置数据;
* isAreaText-是否在图标中加域; <br>
* areaText-域中文字,lowpress-域的最低刻度;uperpress-域的最高刻度 <br>
* 返 回 值:JFreeChart <br>
*/
@SuppressWarnings("deprecation")
public static JFreeChart createSeriesChart(String title,
String subtitleStr, String X, String Y,
TimeSeriesCollection dataset, boolean isAreaText, String areaText,
double lowpress, double uperpress) { // 时间曲线元素
// JFreeChart chart =
// ChartFactory.createTimeSeriesChart("标题","x轴标志","y轴标志","设置数据",是否显示图形,是否进行提示,是否配置报表存放地址);
JFreeChart chart = ChartFactory.createTimeSeriesChart(title, X, Y,
dataset, true, true, false);
if (subtitleStr != null) {
TextTitle subtitle = new TextTitle(subtitleStr, new Font("黑体",
Font.PLAIN, 12));
chart.addSubtitle(subtitle);
}
// 设置日期显示格式
XYPlot plot = chart.getXYPlot();
DateAxis axis = (DateAxis) plot.getDomainAxis();
axis.setDateFormatOverride(new SimpleDateFormat("yyyy-MM-dd"));
// 设置标题的颜色
chart.setTitle(new TextTitle(title, new Font("黑体", Font.PLAIN, 22)));
chart.setBackgroundPaint(new GradientPaint(0, 0, Color.white, 0, 1000,
Color.blue));
plot.setOutlineStroke(new BasicStroke(1.5f)); // 边框粗细
ValueAxis vaxis = plot.getDomainAxis();
vaxis.setAxisLineStroke(new BasicStroke(1.5f)); // 坐标轴粗细
vaxis.setAxisLinePaint(new Color(215, 215, 215)); // 坐标轴颜色
vaxis.setLabelPaint(new Color(10, 10, 10)); // 坐标轴标题颜色
vaxis.setTickLabelPaint(new Color(102, 102, 102)); // 坐标轴标尺值颜色
vaxis.setLowerMargin(0.06d);// 分类轴下(左)边距
vaxis.setUpperMargin(0.14d);// 分类轴下(右)边距,防止最后边的一个数据靠近了坐标轴。
plot.setNoDataMessage("找不到可用数据");// 没有数据时显示的文字说明。
XYLineAndShapeRenderer xylineandshaperenderer = (XYLineAndShapeRenderer) plot
.getRenderer();
// 第一条折线的颜色
xylineandshaperenderer.setBaseItemLabelsVisible(true);
xylineandshaperenderer.setSeriesFillPaint(0, new Color(127, 128, 0));
xylineandshaperenderer.setSeriesPaint(0, new Color(127, 128, 0));
xylineandshaperenderer.setSeriesShapesVisible(0, true);
xylineandshaperenderer.setSeriesShapesVisible(1, true);
xylineandshaperenderer.setSeriesShapesVisible(2, true);
xylineandshaperenderer.setSeriesShapesVisible(3, true);
xylineandshaperenderer.setSeriesShapesVisible(4, true);
// 折线的粗细调
StandardXYToolTipGenerator xytool = new StandardXYToolTipGenerator();
xylineandshaperenderer.setToolTipGenerator(xytool);
xylineandshaperenderer.setStroke(new BasicStroke(1.5f));
// 显示节点的值
xylineandshaperenderer.setBaseItemLabelsVisible(true);
xylineandshaperenderer
.setBasePositiveItemLabelPosition(new ItemLabelPosition(
ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_CENTER));
xylineandshaperenderer
.setBaseItemLabelGenerator(new StandardXYItemLabelGenerator());
xylineandshaperenderer.setBaseItemLabelPaint(new Color(102, 102, 102));// 显示折点数值字体的颜色
ValueAxis rangeAxis = plot.getRangeAxis();
// 设置最高的一个Item与图片顶端的距离
rangeAxis.setUpperMargin(0.2);
// 设置最低的一个Item与图片底端的距离
rangeAxis.setLowerMargin(0.3);
// 在图表中加区域加区域
if (isAreaText) {
lowpress = 62;
uperpress = 400;
IntervalMarker intermarker = new IntervalMarker(lowpress, uperpress);
intermarker.setPaint(Color.decode("#66FFCC"));// 域顏色
intermarker.setLabelFont(new Font("SansSerif", 41, 14));
intermarker.setLabelPaint(Color.RED);
intermarker.setLabel(areaText);
if (dataset != null) {
plot.addRangeMarker(intermarker, Layer.BACKGROUND);
}
}
return chart;
}
/**
* * 横向图
*
* @param dataset
* 数据集
* @param xName
* x轴的说明(如种类,时间等)
* @param yName
* y轴的说明(如速度,时间等)
* @param chartTitle
* 图标题
* @param charName
* 生成图片的名字
* @return
*/
public static JFreeChart createHorizontalBarChart(CategoryDataset dataset,
String xName, String yName, String chartTitle, String charName) {
JFreeChart chart = ChartFactory.createBarChart(chartTitle, // 图表标题
xName, // 目录轴的显示标签
yName, // 数值轴的显示标签
dataset, // 数据集
PlotOrientation.VERTICAL, // 图表方向:水平、垂直
true, // 是否显示图例(对于简单的柱状图必须是false)
false, // 是否生成工具
false // 是否生成URL链接
);
CategoryPlot plot = chart.getCategoryPlot();
// 数据轴精度
NumberAxis vn = (NumberAxis) plot.getRangeAxis();
// 设置刻度必须从0开始
// vn.setAutoRangeIncludesZero(true);
DecimalFormat df = new DecimalFormat("#0.00");
vn.setNumberFormatOverride(df); // 数据轴数据标签的显示格式
CategoryAxis domainAxis = plot.getDomainAxis();
domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45); // 横轴上的
// Lable
Font labelFont = new Font("SansSerif", Font.PLAIN, 12);
domainAxis.setLabelFont(labelFont);// 轴标题
domainAxis.setTickLabelFont(labelFont);// 轴数值
domainAxis.setMaximumCategoryLabelWidthRatio(0.8f);// 横轴上的 Lable 是否完整显示
// domainAxis.setVerticalCategoryLabels(false);
plot.setDomainAxis(domainAxis);
ValueAxis rangeAxis = plot.getRangeAxis();
// 设置最高的一个 Item 与图片顶端的距离
rangeAxis.setUpperMargin(0.15);
// 设置最低的一个 Item 与图片底端的距离
rangeAxis.setLowerMargin(0.15);
plot.setRangeAxis(rangeAxis);
BarRenderer renderer = new BarRenderer();
// 设置柱子宽度
renderer.setMaximumBarWidth(0.03);
// 设置柱子高度
renderer.setMinimumBarLength(30);
renderer.setBaseOutlinePaint(Color.BLACK);
// 设置柱的颜色
renderer.setSeriesPaint(0, Color.GREEN);
renderer.setSeriesPaint(1, new Color(0, 0, 255));
// 设置每个地区所包含的平行柱的之间距离
renderer.setItemMargin(0.5);
// 显示每个柱的数值,并修改该数值的字体属性
renderer
.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
// 设置柱的数值可见
renderer.setBaseItemLabelsVisible(true);
plot.setRenderer(renderer);
// 设置柱的透明度
plot.setForegroundAlpha(0.6f);
return chart;
}
/**
* * 折线图
*
* @param chartTitle
* @param x
* @param y
* @param xyDataset
* @param charName
* @return
*/
public static JFreeChart createFoldLineChar(String chartTitle, String x,
String y, CategoryDataset xyDataset, String charName) {
JFreeChart chart = ChartFactory.createLineChart(chartTitle, x, y,
xyDataset, PlotOrientation.VERTICAL, true, true, false);
chart.setTitle(new TextTitle(chartTitle,
new Font("黑体", Font.ITALIC, 22)));
chart.setTextAntiAlias(false);
chart.setBackgroundPaint(Color.WHITE);
// 设置图标题的字体重新设置title
Font font = new Font("黑书", Font.BOLD, 25);
TextTitle title = new TextTitle(chartTitle);
title.setFont(font);
chart.setTitle(title);
// 设置面板字体
Font labelFont = new Font("SansSerif", Font.TRUETYPE_FONT, 12);
chart.setBackgroundPaint(Color.WHITE);
CategoryPlot categoryplot = (CategoryPlot) chart.getPlot();
// x轴 // 分类轴网格是否可见
categoryplot.setDomainGridlinesVisible(true);
// y轴 //数据轴网格是否可见
categoryplot.setRangeGridlinesVisible(true);
categoryplot.setRangeGridlinePaint(Color.WHITE);// 虚线色彩
categoryplot.setDomainGridlinePaint(Color.WHITE);// 虚线色彩
categoryplot.setBackgroundPaint(Color.lightGray);
// 设置轴和面板之间的距离
// categoryplot.setAxisOffset(new RectangleInsets(5D, 5D, 5D, 5D));
CategoryAxis domainAxis = categoryplot.getDomainAxis();
domainAxis.setLabelFont(new Font("宋体", Font.PLAIN, 20));// x轴标题文字
domainAxis.setTickLabelFont(new Font("宋体", Font.PLAIN, 10));// x轴坐标上文字
chart.getLegend().setItemFont(new Font("宋体", Font.PLAIN, 12));// 图例文字
domainAxis.setLabelFont(labelFont);// 轴标题
domainAxis.setTickLabelFont(labelFont);// 轴数值
// 45度倾斜
// domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);
// // 横轴上的
// 解决X轴字数过长出现省略号的问题
domainAxis.setMaximumCategoryLabelLines(10);// 行数,根据需要自己设
domainAxis.setMaximumCategoryLabelWidthRatio(1);// 每行宽度,这里设一个汉字宽
// Lable
// 设置距离图片左端距离
domainAxis.setLowerMargin(0.0);
// 设置距离图片右端距离
domainAxis.setUpperMargin(0.0);
NumberAxis numberaxis = (NumberAxis) categoryplot.getRangeAxis();
numberaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
numberaxis.setAutoRangeIncludesZero(true);
numberaxis.setLabelFont(new Font("宋体", Font.PLAIN, 15));// y轴标题文字
numberaxis.setTickLabelFont(new Font("宋体", Font.PLAIN, 10));// y轴坐标上文字
// 获得renderer 注意这里是下嗍造型到lineandshaperenderer!!
LineAndShapeRenderer lineandshaperenderer = (LineAndShapeRenderer) categoryplot
.getRenderer();
lineandshaperenderer.setBaseShapesVisible(true); // series 点(即数据点)可见
lineandshaperenderer.setBaseLinesVisible(true); // series 点(即数据点)间有连线可见
// 显示折点数据
// lineandshaperenderer.setBaseItemLabelGenerator(new
// StandardCategoryItemLabelGenerator());
// lineandshaperenderer.setBaseItemLabelsVisible(true);
return chart;
}
}
此外,还需要一个封装报表参数的实体类。
package com.bdqn.entity;
public class ChartParams {
/**
* 标题
*
* @deprecated bigboss取代
*/
public String chartTitle;
/**
* 饼图 pie
*/
public String chartType;
/**
* 时长单位
*/
public String scdw;
public String getScdw() {
return scdw;
}
public void setScdw(String scdw) {
this.scdw = scdw;
}
/**
* 编目状态
*/
public String bmzt;
public String getBmzt() {
return bmzt;
}
public void setBmzt(String bmzt) {
this.bmzt = bmzt;
}
public String getBigboss() {
return bigboss;
}
public void setBigboss(String bigboss) {
this.bigboss = bigboss;
}
/**
* 开始时间
*/
public String interTime;
/**
* 结束时间
*/
public String endTime;
/**
* 大类 1 YPLX
*/
public String bigboss;
public String getInterTime() {
return interTime;
}
public void setInterTime(String interTime) {
this.interTime = interTime;
}
public String getEndTime() {
return endTime;
}
public void setEndTime(String endTime) {
this.endTime = endTime;
}
/**
* 标题
*
* @deprecated bigboss取代
*/
public String getChartTitle() {
return chartTitle;
}
/**
* 标题
*
* @deprecated bigboss取代
*/
public void setChartTitle(String chartTitle) {
this.chartTitle = chartTitle;
}
public String getChartType() {
return chartType;
}
public void setChartType(String chartType) {
this.chartType = chartType;
}
}
此外,由于我是用得struts2框架,故而需要如此配置:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="jfreechart" extends="struts-default">
<!-- 自定义返回类型 -->
<result-types>
<!--
<result-type name="chart" class="org.apache.struts2.dispatcher.ChartResult"></result-type>
-->
<result-type name="chart" class="com.bdqn.util.ChartResult"></result-type>
</result-types>
<action name="jfreechart_*" class="com.bdqn.action.JFreechartAction" method="{1}">
<!--
<result type="chart">
<param name="width">400</param>
<param name="height">300</param>
</result>
-->
<result type="chart">
<param name="width">500</param>
<param name="height">400</param>
<param name="imageType">png</param>
</result>
<result name="chooseParams">/chartConfig.jsp</result>
<result name="createtable">/chartTable.jsp</result>
<result name="chartshow">/chartshow.jsp</result>
<result name="HAVEINFO">/Return.jsp</result>
</action>
</package>
</struts>
此类以便返回不同类型:
package com.bdqn.util;
import java.io.OutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.StrutsResultSupport;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import com.opensymphony.xwork2.ActionInvocation;
public class ChartResult extends StrutsResultSupport {
/**
*
*/
private static final long serialVersionUID = 4199494785336139337L;
//图片宽度
private int width;
//图片高度
private int height;
//图片类型 jpg,png
private String imageType;
@Override
protected void doExecute(String arg0, ActionInvocation invocation) throws Exception {
JFreeChart chart =(JFreeChart) invocation.getStack().findValue("chart");
HttpServletResponse response = ServletActionContext.getResponse();
OutputStream os = response.getOutputStream();
if("jpeg".equalsIgnoreCase(imageType) || "jpg".equalsIgnoreCase(imageType))
ChartUtilities.writeChartAsJPEG(os, chart, width, height);
else if("png".equalsIgnoreCase(imageType))
ChartUtilities.writeChartAsPNG(os, chart, width, height);
else
ChartUtilities.writeChartAsJPEG(os, chart, width, height);
os.flush();
}
public void setHeight(int height) {
this.height = height;
}
public void setWidth(int width) {
this.width = width;
}
public void setImageType(String imageType) {
this.imageType = imageType;
}
}
页面上:为了不使其自动产生图,由于我还要添加其他内容,所以需要如此写:
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ page language="java" import="java.util.*,com.bdqn.entity.ChartParams;" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<%
ChartParams chartparams = (ChartParams) request.getAttribute("chartparams");
%>
<jsp:include page="nocache.jsp"></jsp:include>
<script type="text/javascript">
function printpr() //预览函数
{
document.getElementById("bo").style.display="none"; //打印之前先隐藏不想打印输出的元素(此例中隐藏“打印”和“打印预览”两个按钮)
var OLECMDID = 7;
var PROMPT = 1;
var WebBrowser = '<OBJECT ID="WebBrowser1" WIDTH="0" HEIGHT="0" CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></OBJECT>';
document.body.insertAdjacentHTML('beforeEnd', WebBrowser);
WebBrowser1.ExecWB(OLECMDID, PROMPT);
WebBrowser1.outerHTML = "";
document.getElementById("bo").style.display="";//打印之后将该元素显示出来(显示出“打印”和“打印预览”两个按钮,方便别人下次打印)
}
function printTure() //打印函数
{
document.getElementById("bo").style.display="none";
window.print();
document.getElementById("bo").style.display="";
}
function doPage()
{
layLoading.style.display = "none";//同上
}
</SCRIPT>
</head>
<body>
<div id="bo">
<OBJECT id="WebBrowser" classid="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2" height="0" width="0" >
</OBJECT>
<input type= "button" value= "打印 " onclick= "printTure()">
<input type="button" value="打印预览" onclick="printpr()">
</div>
<img src="jfreechart_createChart?chartparams.scdw=<%=chartparams.getScdw()%>&chartparams.chartType=<%=chartparams.getChartType() %>&chartparams.bmzt=<%=chartparams.getBmzt()%>&chartparams.bigboss=<%=chartparams.getBigboss()%>&chartparams.interTime=<%=chartparams.getInterTime()%>&chartparams.endTime=<%=chartparams.getEndTime()%>"><br/>
</body>
</html>
效果如下:
有什么疑问联系我~QQ271020396