用JFreeChart统计报表

 

需要包: jcommon-1.0.16.jar、jfreechart-1.0.13.jar

 

1. 创建图表工具类 JFreeChartUtils.java

package com.pcm.fnd.util;

import java.awt.Color;
import java.awt.Font;
import java.text.DecimalFormat;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.NumberTickUnit;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.category.CategoryDataset;

/**
 * 创建图表工具类
 * @author qiyh
 * @date 2011-08-10
 *
 */
public class JFreeChartUtils {

 /**
   * 折线图
   * @param chartTitle:
   *    标题
   * @param showX:
   *   X轴显示的说明文字
   * @param showY:
   *   Y轴显示的说明文字
   * @param xyDataset:
   *   数据集
   * @param maxrange:
   *   Y轴最大值
   * @param showCornerValue:
   *         是否在拐点数据值
   * @return JFreeChart
   */
   public static JFreeChart createLineXYChart(String chartTitle, String showX, String showY,
           CategoryDataset xyDataset, double maxrange, boolean showCornerValue) {

       JFreeChart chart = ChartFactory.createLineChart(chartTitle, showX, showY,
               xyDataset, PlotOrientation.VERTICAL, true, true, false);

//       chart.setTextAntiAlias(false);
       // 设置背景
       chart.setBackgroundPaint(Color.WHITE);
       // 设置标题title
       Font font = new Font("隶书", Font.PLAIN, 25);
       TextTitle title = new TextTitle(chartTitle);
       title.setFont(font);
       chart.setTitle(title);
      
       // 设置面板字体
       Font labelFont = new Font("宋体", Font.CENTER_BASELINE, 12);
       Font kfont = new Font("宋体", Font.CENTER_BASELINE, 13);// 底部图例
      
       chart.getLegend().setItemFont(kfont);
       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));
       //没有数据时显示的文字说明。
       categoryplot.setNoDataMessage("没有数据!");
       categoryplot.setNoDataMessagePaint(Color.RED);
      
       // X轴
       CategoryAxis domainAxis = categoryplot.getDomainAxis();
       domainAxis.setLabelFont(labelFont);// x轴标题字体设置
       domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45); // x横轴上45度倾斜
       //设置最低的一个   Item   与图片底端的距离
       domainAxis.setLowerMargin(0.0);
       //设置最高的一个   Item   与图片顶端的距离
       domainAxis.setUpperMargin(0.0);

       // Y轴
       ValueAxis rangeAxisv = categoryplot.getRangeAxis();
       rangeAxisv.setLabelFont(labelFont);// y轴字体设置
       rangeAxisv.setTickLabelFont(labelFont);// y轴字体设置
      
      
       // 数
       NumberAxis rangeAxis = (NumberAxis) categoryplot.getRangeAxis();
       // 格式化
       DecimalFormat decimalFormat = new DecimalFormat("0.0");
       rangeAxis.setNumberFormatOverride(decimalFormat);
    //设置Y轴的最小值
    rangeAxis.setLowerBound(0);
    //设置Y轴间隔单位
    rangeAxis.setTickUnit(new NumberTickUnit(5D));
    //设置Y轴的最大值
    rangeAxis.setUpperBound(maxrange+3D);

      
       // 获得renderer 注意这里是下嗍造型到lineandshaperenderer!!
       LineAndShapeRenderer lineandshaperenderer = (LineAndShapeRenderer) categoryplot.getRenderer();

       lineandshaperenderer.setBaseShapesVisible(true); // series 点(即数据点)可见

       lineandshaperenderer.setBaseLinesVisible(true); // series 点(即数据点)间有连线可见

       // 显示折点数据
       if (showCornerValue) {
        lineandshaperenderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
           lineandshaperenderer.setBaseItemLabelsVisible(true);
       }
      
       return chart;
   }
}


 

2. 请求服务器中的action
/**
  * 率(百分比)
  * @param mapping
  * @param form
  * @param request
  * @param response
  * @return
  * @throws Exception
  * @author qiyh
  */
 public ActionForward showRate(ActionMapping mapping, ActionForm form,
   HttpServletRequest request, HttpServletResponse response)
   throws Exception {

  // 初始化跳转页面
  String forwordName = "showFaultAmountRate";

  StatBIListForm theForm = (StatBIListForm) form;
  FaultRateVO faultRateVo = theForm.getFaultRateVo();
  
  // 当前时间
  Calendar cl = Calendar.getInstance();
  cl.setTime(new Date());
  if (null == faultRateVo.getBeginYear()) {
   faultRateVo.setBeginYear(String.valueOf(cl.get(Calendar.YEAR)-1));
  }
  if (null == faultRateVo.getBeginMonth()) {
   faultRateVo.setBeginMonth(String.valueOf(cl.get(Calendar.MONTH)+1));
  }
  if (null == faultRateVo.getEndYear()) {
   faultRateVo.setEndYear(String.valueOf(cl.get(Calendar.YEAR)));
  }
  if (null == faultRateVo.getEndMonth()) {
   faultRateVo.setEndMonth(String.valueOf(cl.get(Calendar.MONTH)));
  }
  
  Date beginDate = parseStrToDate(faultRateVo.getBeginYear(), faultRateVo.getBeginMonth());
  Date endDate = parseStrToDate(faultRateVo.getEndYear(), faultRateVo.getEndMonth());
  // 参数
  Map paraMap = new HashMap();
  paraMap.put("beginDate",beginDate);
  paraMap.put("endDate",endDate);

  // 统计维度
  String dimensionality = faultRateVo.getDimensionality();
  StatBIListService statBIListService = (StatBIListService) this.getBeanFactory("statBIListService");
  List getRate_list = null;
  
   if ("models".equals(dimensionality)) {
   List searchContentList = new ArrayList();
   String searchContents = faultRateVo.getSearchContent();
   if (null != searchContents) {
    searchContents = searchContents.trim().replaceAll(",", ",");
    if (0 < searchContents.indexOf(",")) {
     String[] arry = searchContents.split(",");
     for (int i = 0; i < arry.length; i++) {
      searchContentList.add(arry[i]);
     }
    }else {
     searchContentList.add(searchContents);
    }
   }
   paraMap.put("searchContentArry", searchContentList);

   // 从业务逻辑层查询数据列表
   getRate_list = statBIListService.queryForList("StatBIList.showFaultAmountRateByModels", paraMap);
  }
  
 // 生成图表 
        String rateUrl = getRateUrl("故障损失率分析", getRate_list, false, request);
       
        request.setAttribute("rateUrl", rateUrl);
        theForm.setDataList(getRate_list);
  // 跳转到相应的页面
  return mapping.findForward(forwordName);
 }
 
 /**
  * 生成图表
  * @param title
  *   标题
  * @param dataList
  *   数据
  * @param showValue
  *   是否在拐点显示值
  * @param request
  *   request
  * @return
  */
 private String getRateUrl(String title, List dataList, boolean showValue, HttpServletRequest request){
  String filename = null;
  // 定义y轴最大值
  double maxrange = 0D;
  // 数据集
  DefaultCategoryDataset line_dataset = new DefaultCategoryDataset();
  if (null != dataList) {
         for (Iterator iterator = dataList.iterator(); iterator.hasNext();) {
          FaultRateVO faultAmountRateVo = (FaultRateVO) iterator.next();
          if (null != faultAmountRateVo && null != faultAmountRateVo.getYearm()) {
           // 统计实体
              String statEntity = faultAmountRateVo.getStatEntity() != null ? faultAmountRateVo.getStatEntity() : "";
              // 率
              double rate = Double.parseDouble(faultAmountRateVo.getRate() != null ? faultAmountRateVo.getRate() : "0.00");
              // 年月
              String yearm = faultAmountRateVo.getYearm() != null ? faultAmountRateVo.getYearm() : "0";
              
              maxrange = maxrange > rate ? maxrange : rate;
              
              // 将数据添加至列表 
              line_dataset.addValue(rate, statEntity, yearm);
    }
         }
  }

        // 调用工具类生成折线图
        JFreeChart chart = JFreeChartUtils.createLineXYChart(title, null, "占有率%", line_dataset, maxrange, showValue);
        try {
            filename = ServletUtilities.saveChartAsPNG(chart, 600, 400, null, request.getSession());
        } catch (IOException e) {
            e.printStackTrace();
        }
        String graphURL = request.getContextPath() + "/servlet/DisplayChart?filename=" + filename;

        return graphURL;
 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值