struts2+JfreeChart實現餅狀圖,柱狀圖,線形圖

1.基本原理:Jfreechart類生成圖片(在tomcat-->temp目錄下),再在頁面中用<img src="路徑"/>輸出

2.導入jar包

commons-logging-1.0.4.jar,freemarker-2.3.8.jar,ognl-2.6.11.jar,struts2-core-2.0.12.jar,xwork-2.0.6.jar

jcommon-1.0.16.jar,jfreechart-1.0.13.jar

3.定義web.xml

<filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
   
   
    <servlet>
     <servlet-name>display</servlet-name>
     <servlet-class>org.jfree.chart.servlet.DisplayChart</servlet-class>
     
    </servlet>
    <servlet-mapping>
     <servlet-name>display</servlet-name>
     <url-pattern>/servlet/displaychart</url-pattern>
    </servlet-mapping>
   
    <!-- 指定Session過期後,自動刪除tomcat目錄下的temp文件夾內的圖片 -->
    <listener>
     <listener-class>org.jfree.chart.servlet.ChartDeleter</listener-class>
     
    </listener>

4.定義JFreechartFactory類,用來生成餅狀,柱狀,線性JreeChart對象

package com.jfreechart;

import java.awt.Color;
import java.awt.Font;

import org.jfree.chart.*;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.title.LegendTitle;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.general.DatasetUtilities;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.ui.RectangleInsets;
import org.jfree.ui.TextAnchor;
import org.jfree.util.Rotation;

import org.jfree.chart.axis.AxisLocation;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.renderer.category.BarRenderer3D;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.chart.labels.*;
import org.jfree.chart.plot.*;
import org.jfree.data.time.*;

public class JFreeChartFactory {

 
 public static JFreeChart CreateBarChart()
 {
  // 生成普通餅圖
   JFreeChart chart = ChartFactory.createBarChart3D
("", "肉類", "銷量",
     getBarDateSet(),
     PlotOrientation.VERTICAL, true, false, false);
   // 重新設置圖表標題,改變字體
   chart.setTitle(new TextTitle("肉量銷售圖"
    , new Font("黑體", Font.ITALIC , 22)));
   // 取得統計圖表的第一個圖例
   LegendTitle legend = chart.getLegend(0);
   // 修改圖例的字體(解決亂碼)
   legend.setItemFont(new Font("宋體", Font.BOLD, 14));
   // 獲得餅圖的 Plot 對象
   CategoryPlot plot = chart.getCategoryPlot();
  
   ValueAxis valueAxis=plot.getRangeAxis();
  
   valueAxis.setLabelFont(new Font("楷體", Font.BOLD, 14));//設置y軸的標題(解決亂碼問題)
   valueAxis.setTickLabelFont(new Font("楷體", Font.BOLD, 14));//設置y軸上的文字(解決亂碼問題)
  
   //valueAxis.setAutoRange(true);
   //valueAxis.setFixedAutoRange(50);
   valueAxis.setAutoRangeMinimumSize(50);
   valueAxis.setLowerBound(0);
   valueAxis.setUpperBound(700);
  
   plot.getDomainAxis().setLabelFont(new Font("楷體", Font.BOLD, 14));//設置x軸的標題(解決亂碼問題)
   plot.getDomainAxis().setTickLabelFont(new Font("楷體", Font.BOLD, 14));//設置x軸上的文字(解決亂碼問題)
  
   //設置背景色
   plot.setBackgroundPaint(Color.white);
  
   //設置y軸的線條顏色
   plot.setDomainGridlinePaint(Color.PINK);
  //設置x軸的線條顏色
   plot.setRangeGridlinePaint(Color.PINK);
  
  
   BarRenderer3D renderer=new BarRenderer3D();
   renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
   renderer.setBaseItemLabelsVisible(true);
  
   //注意:此句很關鍵,若無此句,那數字的顯示會被覆蓋,給人數字沒有顯示出來的問題
   renderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12,TextAnchor.BASELINE_LEFT));
   renderer.setItemLabelAnchorOffset(10D);
  
   plot.setRenderer(renderer);
  
   //將下方的“肉類”放到上方
  // plot.setDomainAxisLocation(AxisLocation.TOP_OR_RIGHT);
   //將默認放在左邊的“銷量”放到右方
   plot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_RIGHT);
  
  
   // 設定背景透明度(0-1.0 之間)
   plot.setBackgroundAlpha(0.9f);
  
   return chart;
 }
 
 private static CategoryDataset getBarDateSet()
 {
  double da[][]=new double[][]{{200,340,400},
    {300,640,200},
    {400,340,100}};
  String row[]={"豬肉","狗肉","羊肉"};
  String colu[]={"廣州","深圳","上海"};
  
  return DatasetUtilities.createCategoryDataset(row, colu, da);
  
 }
 
 public static JFreeChart CreateLineChart()
 {
  
  
  JFreeChart chart = ChartFactory.createTimeSeriesChart("訪問量統計時間線","月份",
    "訪問量",getLineDateSet(),true,true,true);
  
  
  
  
  
  //設置子標題
  TextTitle subtitle=new TextTitle("2007年度",new Font("黑體",Font.BOLD,12));
  chart.addSubtitle(subtitle);
  //設置主標題
  chart.setTitle(new TextTitle("阿蜜果blog訪問量統計",new Font("隸書",Font.ITALIC,15)));
  
  
  // 取得統計圖表的第一個圖例
   LegendTitle legend = chart.getLegend(0);
   // 修改圖例的字體(解決亂碼)
   legend.setItemFont(new Font("宋體", Font.BOLD, 14));
  
   XYPlot plot = chart.getXYPlot();
  
   ValueAxis valueAxis=plot.getRangeAxis();
  
   valueAxis.setLabelFont(new Font("楷體", Font.BOLD, 14));//設置y軸的標題(解決亂碼問題)
   valueAxis.setTickLabelFont(new Font("楷體", Font.BOLD, 14));//設置y軸上的文字(解決亂碼問題)
  
   plot.getDomainAxis().setLabelFont(new Font("楷體", Font.BOLD, 14));//設置x軸的標題(解決亂碼問題)
   plot.getDomainAxis().setTickLabelFont(new Font("楷體", Font.BOLD, 14));//設置x軸上的文字(解決亂碼問題)
  
  
  
  //設置網格背景顏色
   plot.setBackgroundPaint(Color.white);
   //設置網格豎線顏色
   plot.setDomainGridlinePaint(Color.BLUE);
   //設置網格橫線顏色
   plot.setRangeGridlinePaint(Color.pink);
   //設置曲線圖與xy軸的距離
   plot.setAxisOffset(new RectangleInsets(0D, 0D, 0D, 10D));
  
  // XYLineAndShapeRenderer xylineandshaperenderer = (XYLineAndShapeRenderer)plot.getRenderer();
   //xylineandshaperenderer.setBaseItemLabelsVisible(true);
  
  //設置曲線顯示各數據點的值
   XYItemRenderer xyitem = plot.getRenderer();  
   xyitem.setBaseItemLabelsVisible(true); 
    xyitem.setBasePositiveItemLabelPosition(
     new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12,
       TextAnchor.BASELINE_LEFT));
   xyitem.setBaseItemLabelGenerator(new
     StandardXYItemLabelGenerator());
   xyitem.setBaseItemLabelFont(new Font("Dialog", 1, 14));
   plot.setRenderer(xyitem);
  
  chart.setAntiAlias(true);
  return chart;
 }
 
 private static TimeSeriesCollection getLineDateSet()
 {
  //訪問量統計時間線
  TimeSeries timeSeries1=new TimeSeries("2010",Month.class);
  TimeSeries timeSeries2=new TimeSeries("2011",Month.class);
  //時間曲線數據集合
  TimeSeriesCollection lineDataset=new TimeSeriesCollection();
  //構造數據集合
  timeSeries1.add(new Month(1,2011), 11200);
  timeSeries1.add(new Month(2, 2011), 9000);
  timeSeries1.add(new Month(3, 2011), 6200);
  timeSeries1.add(new Month(4, 2011), 8200);
  timeSeries1.add(new Month(5, 2011), 8200);
  timeSeries1.add(new Month(6, 2011), 12200);
  timeSeries1.add(new Month(7, 2011), 13200);
  
  timeSeries2.add(new Month(1,2011), 1120);
  timeSeries2.add(new Month(2, 2011), 800);
  timeSeries2.add(new Month(3, 2011), 3200);
  timeSeries2.add(new Month(4, 2011), 2200);
  timeSeries2.add(new Month(5, 2011), 1200);
  timeSeries2.add(new Month(6, 2011), 62200);
  timeSeries2.add(new Month(7, 2011), 3200);
  
  lineDataset.addSeries(timeSeries1);
  lineDataset.addSeries(timeSeries2);
  return lineDataset;
 }
 
 
 public static JFreeChart CreatePieChart()
 {
  // 生成普通餅圖
   JFreeChart chart = ChartFactory.createPieChart3D(
   "",  // 圖表標題
   getPieDataSet(), // 數據
    true, // 是否顯示圖例
    true, // 是否顯示工具提示
    false // 是否生成 URL
   );
   // 重新設置圖表標題,改變字體
   chart.setTitle(new TextTitle("圖書銷量統計圖"
    , new Font("黑體", Font.ITALIC , 14)));
   // 取得統計圖表的第一個圖例
   LegendTitle legend = chart.getLegend(0);
   // 修改圖例的字體
   legend.setItemFont(new Font("宋體", Font.BOLD, 12));
   // 獲得餅圖的 Plot 對象
   PiePlot plot = (PiePlot)chart.getPlot();
   // 設置餅圖各部分的標籤字體
   plot.setLabelFont(new Font("楷體", Font.BOLD, 12));
  
  
  
  
  //設置開始角度
   plot.setStartAngle(150D);
   //設置方向爲”順時針方向“
   plot.setDirection(Rotation.CLOCKWISE);
   //設置透明度,0.5F爲半透明,1爲不透明,0爲全透明
   plot.setForegroundAlpha(0.5F);
  
   // 設定背景透明度(0-1.0 之間)
   plot.setBackgroundAlpha(0.9f);
  
   return chart;
 }
 
 private static  DefaultPieDataset getPieDataSet()
  {
   // 提供生成餅圖的數據
   DefaultPieDataset dataset = new DefaultPieDataset();
   dataset.setValue("瘋狂 Java 講義",47000);
   dataset.setValue("輕量級 Java EE 企業實戰",38000);
   dataset.setValue("瘋狂 Ajax 講義",31000);
   dataset.setValue("Struts 2 權威指南",29000);
   dataset.setValue("瘋狂 XML 講義",25000);
   return dataset;
  }
 
}

5.定義Action類(定義3個屬性,分別用來存儲餅狀,柱狀,線性圖片的輸出路徑)

package com.test.action;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import com.opensymphony.xwork2.ActionSupport;

import com.jfreechart.*;

import org.apache.struts2.ServletActionContext;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.servlet.ServletUtilities;
import org.jfree.chart.servlet.DisplayChart;

public class LoginAction extends ActionSupport {

 /**
  *
  */
 
 private String username;
 private String pwd;
 
 private String barchart;
 private String linechart;
 private String piechart;
 public String getUsername() {
  return username;
 }
 public void setUsername(String username) {
  this.username = username;
 }
 public String getPwd() {
  return pwd;
 }
 public void setPwd(String pwd) {
  this.pwd = pwd;
 }
 
 public String ForwardLogin()
 {
  return "input";
 }
 
 public String execute() throws Exception
 {
  CreatePie();
  CreateLine();
  CreateBar();
  //System.out.println("execute");
  return "first";
 }
 
 
 


 
 
 public String getBarchart() {
  return barchart;
 }
 public void setBarchart(String barchart) {
  this.barchart = barchart;
 }
 public String getLinechart() {
  return linechart;
 }
 public void setLinechart(String linechart) {
  this.linechart = linechart;
 }
 public String getPiechart() {
  return piechart;
 }
 public void setPiechart(String piechart) {
  this.piechart = piechart;
 }
 
 /**
  * 創建餅形
  * @throws IOException
  */
 private void CreatePie() throws IOException
 {
  HttpServletRequest request=ServletActionContext.getRequest();
  
  JFreeChart chart=JFreeChartFactory.CreatePieChart();
  String st=ServletUtilities.saveChartAsJPEG(chart,500,400,request.getSession());
  
  piechart=new StringBuffer(request.getContextPath()).append("/servlet/displaychart?filename="+st).toString();
  
 }
 
 /**
  * 創建線性
  * @throws IOException
  */
 private void CreateLine() throws IOException
 {
  HttpServletRequest request=ServletActionContext.getRequest();
  
  JFreeChart chart=JFreeChartFactory.CreateLineChart();
  String st=ServletUtilities.saveChartAsJPEG(chart,500,400,request.getSession());
  
  linechart=new StringBuffer(request.getContextPath()).append("/servlet/displaychart?filename="+st).toString();
  
 }
 
 /**
  * 創建柱形
  * @throws IOException
  */
 private void CreateBar() throws IOException
 {
  HttpServletRequest request=ServletActionContext.getRequest();
  
  JFreeChart chart=JFreeChartFactory.CreateBarChart();
  String st=ServletUtilities.saveChartAsJPEG(chart,500,400,request.getSession());
  
  barchart=new StringBuffer(request.getContextPath()).append("/servlet/displaychart?filename="+st).toString();
  
 }
 
}

6.定義jsp文件,用<img>標籤輸出圖形

 餅狀<br/>
    <img src="${requestScope.piechart }">
    <br>線形
    <br>
    <img src="${requestScope.linechart }">
    <br> 柱形
    <br>
    <img src="${requestScope.barchart }">

 

發佈了36 篇原創文章 · 獲贊 3 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章