struts2+jsp+jfreechart在JSP页面生成图表

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" />' />

完毕!

效果预览:







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值