1.Action:MessageLogAction.java
/**
* 根據模組名和操作名產生圖
* @return
* @throws AppException
*/
@OperateLog(moduleName = "錯誤記錄檔", content = "走勢分析")
public String goFindMessageLogToCreateChart() {
DefaultCategoryDataset dcd = new DefaultCategoryDataset();
MessageLogSearchForm searchForm = model.getSearchForm();
searchForm.fromJsonString();
List<Object[]> list = messageLogBPO.findMessageLogToCreateChart(
model.getActionname(), model.getMlfcsearchForm());
if (list != null && list.size() > 50) {
list = messageLogBPO.findMessageLogToCreateChartMonth(
model.getActionname(), model.getMlfcsearchForm());
}
if (list != null && list.size() > 0) {
for (int i = 0; i < list.size(); i++) {
dcd.addValue(Integer.valueOf(list.get(i)[0].toString()),
"數量", list.get(i)[1].toString());
}
}
this.chart = JFreeChartUtils.makeChartBar(model.getActionname()
+ " 錯誤走勢", "日期", "數量", new String[] {}, dcd);
return SUCCESS;
}
2.struts.xml設定檔
<!-- 根據模組名和操作名尋找錯誤記錄檔組建圖表 -->
<action name="findMessageLogToCreateChart" class="ap.MessageLogAction" method="goFindMessageLogToCreateChart">
<result name="success" type="chart">
<param name="width">850</param>
<param name="height">400</param>
</result>
</action>
註:需要在
<package name="ap.messagelog" extends="struts-default.xml">,ap.messagelog這個包的父設定檔
struts-default.xml中加上:
<result-types>
<result-type name="chart" class="com.opensymphony.webwork.dispatcher.ChartResult">
</result-type>
</result-types>
3.JFreeChartUtils.java
/**
* 柱狀圖,分:一般柱狀圖和多組柱狀圖
*
* @param titleName
* @param XName
* @param YName
* @param subtitles
* @param dataset
* @return
*/
public static JFreeChart makeChartBar(String titleName,
String XName, String YName, String[] subtitles,
CategoryDataset dataset) {
JFreeChart jfreechart = ChartFactory.createBarChart3D(titleName, XName,
YName, dataset, PlotOrientation.VERTICAL, true, true, false);
Font font = new Font("宋體", Font.BOLD, 20);
TextTitle title = new TextTitle(titleName);
title.setFont(font);
jfreechart.setTitle(title);
if (subtitles != null) {
for (String subtitle : subtitles) {
jfreechart.addSubtitle(new TextTitle(subtitle));
}
}
jfreechart.setBackgroundPaint(Color.white);
CategoryPlot categoryplot = (CategoryPlot) jfreechart.getPlot();
// 設定顯示地區不要黑色邊框
categoryplot.setOutlineVisible(false);
// x軸設定
CategoryAxis categoryaxis = categoryplot.getDomainAxis();
categoryaxis.setCategoryLabelPositions(CategoryLabelPositions
.createUpRotationLabelPositions(1));
categoryaxis.setMaximumCategoryLabelWidthRatio(0.6f);// 橫軸上的 Lable
categoryaxis.setCategoryMargin(0.4);
// 是否完整顯示
// 設定距離圖片左端距離
categoryaxis.setLowerMargin(0.1);
// 設定距離圖片右端距離
categoryaxis.setUpperMargin(0.1);
ValueAxis rangeAxis = categoryplot.getRangeAxis();
rangeAxis.setUpperMargin(0.5);
categoryplot.setDomainAxis(categoryaxis); // 使橫座標設定生效
//設定柱子上顯示的資料旋轉90度,最後一個參數為旋轉的角度值/3.14
ItemLabelPosition itemLabelPosition= new ItemLabelPosition(
ItemLabelAnchor.INSIDE12, TextAnchor.CENTER_RIGHT,
TextAnchor.CENTER_RIGHT, 1.57D);
// 設定不能在柱子上正常顯示的那些數值的顯示方式,將這些數值顯示在柱子外面
ItemLabelPosition itemLabelPositionFallback = new ItemLabelPosition(
ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT,
TextAnchor.HALF_ASCENT_LEFT, -1.57D);
NumberAxis numberaxis = (NumberAxis) categoryplot.getRangeAxis();
numberaxis.setAutoRangeIncludesZero(false);
numberaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
// 設定顯示方式為平面圖形
IntervalBarRenderer intervalBarRender = new IntervalBarRenderer();
categoryplot.setRenderer(0, intervalBarRender);
intervalBarRender.setItemLabelGenerator(new StandardCategoryItemLabelGenerator());
// 設定bar的最小寬度,以保證能顯示數值
intervalBarRender.setMinimumBarLength(0.02);
// 最大寬度
intervalBarRender.setMaximumBarWidth(0.05);
//設定不能正常顯示的柱子label的position
intervalBarRender.setPositiveItemLabelPositionFallback(itemLabelPositionFallback);
intervalBarRender.setNegativeItemLabelPositionFallback(itemLabelPositionFallback);
intervalBarRender.setItemLabelsVisible(true);
intervalBarRender.setBarPainter(new StandardBarPainter());
intervalBarRender.setItemMargin(-0.01);
//設定正常顯示的柱子label的position
intervalBarRender.setPositiveItemLabelPosition(itemLabelPosition);
intervalBarRender.setNegativeItemLabelPosition(itemLabelPosition);
// 解決中文亂碼問題,共要處理這二部分
// 1、對圖裡面的漢字設定,也就是Plot的設定
Font font2 = new Font("宋體", Font.PLAIN, 12); // 設定字型、類型、字型大小
categoryplot.getDomainAxis().setLabelFont(font2);// 相當於橫軸或理解為X軸
categoryplot.getRangeAxis().setLabelFont(font2);// 相當於豎軸理解為Y軸
// 2、下面的方塊地區是 LegendTitle 對象
Font font3 = new Font("宋體", Font.PLAIN, 12); // 設定字型、類型、字型大小
jfreechart.getLegend().setItemFont(font3);// 最下方
// 設定下面的方塊地區不要黑色邊框
jfreechart.getLegend().setFrame(BlockBorder.NONE);
// 設定下面的方塊地區更加清楚
jfreechart.getRenderingHints().put(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
// 設定總的背景顏色
jfreechart.setBackgroundPaint(ChartColor.white);
// 設定標題顏色
jfreechart.getTitle().setPaint(ChartColor.black);
// 獲得圖表對象
CategoryPlot p = jfreechart.getCategoryPlot();
// 沒有資料時顯示
p.setNoDataMessage("無對應的資料,請重新查詢。");
// 設定圖的背景顏色
p.setBackgroundPaint(ChartColor.white);
// 設定表格線顏色
p.setRangeGridlinePaint(ChartColor.red);
return jfreechart;
}
/**
* 得到餅圖
* @param chartTitle 標題
* @param dataset 資料
* @return JFreeChart
*/
public static JFreeChart getChartPie(String chartTitle, PieDataset dataset){
JFreeChart chart = ChartFactory.createPieChart(chartTitle, dataset, true, false, false);
//設定圖表的標題
chart.setTitle(new TextTitle(chartTitle, new Font("宋體", Font.BOLD, 20)));
chart.setBackgroundPaint(Color.white);
//擷取第一個圖例。就是圖表最下面的那行
LegendTitle legend = chart.getLegend(0);
//設定第一個圖例的屬性
legend.setItemFont(new Font("宋體", Font.PLAIN, 12));
legend.setFrame(BlockBorder.NONE);
legend.setBackgroundPaint(new Color(245, 245, 245));
legend.setItemPaint(Color.BLACK);
//獲得餅圖的Plot
PiePlot plot = (PiePlot) chart.getPlot();
plot.setLabelPaint(new Color(41, 41, 41));
plot.setCircular(true);
plot.setBackgroundPaint(Color.white);
plot.setOutlineVisible(false);
plot.setSectionOutlinesVisible(false);
plot.setLabelOutlinePaint(Color.WHITE);
plot.setShadowPaint(new Color(200, 200, 200));
//設定沒有資料時顯示的內容
plot.setNoDataMessage("沒有資料");
//設定Plot樣式,也就是整個圖表中間的部分的顯示樣式
//這些操作只是為了美化,為了更細緻的控製圖表的樣式
plot.setLabelFont(new Font("宋體", Font.PLAIN, 12));
// 圖片中顯示百分比:自訂方式,{0} 表示選項, {1} 表示數值, {2} 表示所佔比例 ,小數點後兩位
plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0}={1}({2})", NumberFormat.getNumberInstance(), new DecimalFormat("0.00%")));
// 圖例顯示百分比:自訂方式, {0} 表示選項, {1} 表示數值, {2} 表示所佔比例
plot.setLegendLabelGenerator(new StandardPieSectionLabelGenerator("{0}"));
chart.setBackgroundPaint(Color.WHITE);
chart.setBorderVisible(false);
chart.getRenderingHints().put(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
return chart;
}
/**
* 產生儀錶盤通用方法
* @param title 標題
* @param center 設定顯示在錶盤中央位置的資訊
* @param standarddialrangeList 設定刻度範圍List
* @param value 當前指標指向的位置
* @return JFreeChart chart
*/
public static JFreeChart generateDashboard(String title, String center, List<StandardDialRange> standarddialrangeList, Double value){
//資料集合對象 此處為DefaultValueDataset
//當前指標指向的位置,即:我們需要顯示的資料
DefaultValueDataset dataset = new DefaultValueDataset(value);
//執行個體化DialPlot
DialPlot dialplot = new DialPlot();
dialplot.setView(0.0D, 0.0D, 1.0D, 1.0D);
//設定資料集合
dialplot.setDataset(dataset);
//開始設定顯示架構結構
StandardDialFrame simpledialframe = new StandardDialFrame();
simpledialframe.setBackgroundPaint(Color.lightGray);
simpledialframe.setForegroundPaint(Color.darkGray);
dialplot.setDialFrame(simpledialframe);
//結束設定顯示架構結構
GradientPaint gradientpaint = new GradientPaint(new Point(), new Color(255, 255, 255), new Point(), new Color(170, 170, 220));
DialBackground dialbackground = new DialBackground(gradientpaint);
dialbackground.setGradientPaintTransformer(new StandardGradientPaintTransformer(GradientPaintTransformType.VERTICAL));
dialplot.setBackground(dialbackground);
//設定顯示在錶盤中央位置的資訊
DialTextAnnotation dialtextannotation = new DialTextAnnotation(center);
dialtextannotation.setFont(new Font("Dialog", 1, 14));
dialtextannotation.setRadius(0.69999999999999996D);
dialplot.addLayer(dialtextannotation);
DialValueIndicator dialvalueindicator = new DialValueIndicator(0);
dialplot.addLayer(dialvalueindicator);
// 儀錶盤的範圍
double lowerBound = 0D;// 最大刻度
double upperBound = 0D;// 最小刻度
for (StandardDialRange standardDialRange : standarddialrangeList) {
if(standardDialRange.getLowerBound() < lowerBound){
lowerBound = standardDialRange.getLowerBound();
}
if(standardDialRange.getUpperBound() > upperBound){
upperBound = standardDialRange.getUpperBound();
}
standardDialRange.setInnerRadius(0.52000000000000002D);
standardDialRange.setOuterRadius(0.55000000000000004D);
dialplot.addLayer(standardDialRange);
}
//根據錶盤的直徑大小(0.88),設定總刻度範圍
StandardDialScale standarddialscale = new StandardDialScale(lowerBound, upperBound, -120D, -300D, 10D, 4);
standarddialscale.setTickRadius(0.88D);
standarddialscale.setTickLabelOffset(0.14999999999999999D);
standarddialscale.setTickLabelFont(new Font("Dialog", 0, 14));
dialplot.addScale(0, standarddialscale);
//設定指標
Pointer pointer = new Pointer();
dialplot.addLayer(pointer);
//執行個體化DialCap
DialCap dialcap = new DialCap();
dialcap.setRadius(0.10000000000000001D);
dialplot.setCap(dialcap);
//產生chart對象
JFreeChart chart = new JFreeChart(dialplot);
//設定標題
chart.setTitle(title);
return chart;
}
/**
* 折線圖
*
* @param titleName 主標題
* @param XName X軸標題
* @param YName Y軸標題
* @param categoryDataset 圖表資料來源
* @return
*/
public static JFreeChart makeChartLine(String titleName, String XName,
String YName, CategoryDataset categoryDataset) {
JFreeChart jfreechart = ChartFactory.createLineChart(titleName, XName,
YName, categoryDataset, PlotOrientation.VERTICAL, true, true, false);
jfreechart.setBackgroundPaint(Color.white);
CategoryPlot categoryplot = (CategoryPlot)jfreechart.getPlot();
CategoryAxis categoryaxis = categoryplot.getDomainAxis();
categoryaxis.setCategoryLabelPositions(CategoryLabelPositions
.createUpRotationLabelPositions(1));
categoryaxis.setMaximumCategoryLabelWidthRatio(0.6f);// 橫軸上的 Lable
NumberAxis numberaxis = (NumberAxis) categoryplot.getRangeAxis();
Font xfont = new Font("宋體", Font.BOLD, 12);// X軸
Font yfont = new Font("宋體", Font.BOLD, 12);// Y軸
Font kfont = new Font("宋體", Font.BOLD, 12);// 底部
Font titleFont = new Font("隸書", Font.BOLD, 18); // 圖片標題
// 圖片標題
jfreechart.setTitle(new TextTitle(jfreechart.getTitle().getText(), titleFont));
// 底部
jfreechart.getLegend().setItemFont(kfont);
// X 軸
categoryaxis.setLabelFont(xfont);// 軸標題
categoryaxis.setTickLabelFont(xfont);// 軸數值
categoryaxis.setTickLabelPaint(Color.black); // 字型顏色
categoryaxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45); // 橫軸上的label斜顯示
// Y 軸
numberaxis.setLabelFont(yfont);
numberaxis.setLabelPaint(Color.black); // 字型顏色
numberaxis.setTickLabelFont(yfont);
categoryplot.setBackgroundPaint(Color.white);
categoryplot.setAxisOffset(new RectangleInsets(5D, 5D, 5D, 5D));
categoryplot.setDomainGridlinePaint(Color.gray);
categoryplot.setRangeGridlinePaint(Color.gray);
LineAndShapeRenderer lineandshaperenderer = (LineAndShapeRenderer) categoryplot.getRenderer();
lineandshaperenderer.setShapesVisible(true);
lineandshaperenderer.setShapesFilled(true);
numberaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
return jfreechart;
}
4.jsp:
<img src='findMessageLogToCreateChart.action?actionname=${actionname}&mlfcsearchForm.startOperateTime=<ww:property value="mlfcsearchForm.startOperateTime" />&mlfcsearchForm.endOperateTime=<ww:property value="mlfcsearchForm.endOperateTime" />' />
完畢。
效果預覽: