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