準備環境:
html
eclipse 3.6
maven 3.0.4
struts 2.1.8
JFreeChart 1.0.9
java
JFreeChart 是一組功能強大、靈活易用的Java繪圖API,使用它能夠生成多種通用性的報表,包括柱狀圖、餅圖、曲線圖、甘特圖等。目前 JFreeChart 的最新版本是 1.0.14,
最近幾天不知爲什麼,sourceforge 網站一直沒法訪問,JFreeChart 如今在官網下載不了了,本人已將現用版本和最新版本上傳至網盤,須要的朋友能夠點擊連接下載:
JFreeChart-1.0.9 :http://115.com/file/e7194ucb#jfreechart-1.0.9.zip
JFreeChart-1.0.14:http://115.com/file/an8lwzqu#jfreechart-1.0.14.zip
聽說,JFreeChart 從 1.0.10 版本開始,圖表的中文字體會變成亂碼,我用 1.0.13 和 1.0.14 兩個版本測試的時候確實是會出現中文亂碼,1.0.9 這個版本不會出現這種狀況,
解決這個亂碼的過程有點繁瑣,並且每種不一樣的圖表的解決方式還不同,但有一點是同樣的,就是修改默認的字體,讓它支持中文字體的顯示,這樣亂碼問題就解決了。
因爲這裏用的 1.0.9 這個版本不會出現中文亂碼問題,因此在這裏姑且不談。接下來會用到 maven 來管理 jar 包,不使用 maven 的朋友能夠直接將 struts2 和 JFreeChart 的
jar 包導進項目裏就 OK 了,maven 不會影響接下來要談的 JFreeChart 柱狀圖的生成。
JFreeChart 所必須的 jar 包:jcommon-1.0.12.jar、jfreechart-1.0.9.jar (這裏說的是 JFreeChart 1.0.9 版本,版本不一樣的請自行對應 jar 包版本)
OK,廢話很少說,直接進入主題:
JFreeChart 組件中有個JFreeChart類,它表明圖表對象。生成任何類型的圖表都要經過該對象,JFreeChart 組件提供了一個工廠類ChartFactory,用來建立各類類型的圖表對象。
建立普通柱狀圖:ChartFactory.createBarChart( … )
建立 3D 柱狀圖:ChartFactory.createBarChart3D( … )
繪製 3D 柱狀圖的方法及方法入口參數:
ChartFactory.createBarChart3D(String title, String categoryAxisLabel, String valueAxisLabel, CategoryDataset dataset, PlotOrientation orientation,
boolean legend, boolean tooltips, boolean urls)
參數1:String title —— 圖表標題
參數2:String categoryAxisLabel —— 統計種類軸標題,能夠理解爲X軸標題
參數3:String valueAxisLabel —— 統計值軸標題,能夠理解爲y軸標題
參數4:CategoryDataset dataset —— 繪圖數據集
參數5:PlotOrientation orientation —— 設定柱形圖的繪製方向,PlotOrientation.VERTICAL(垂直),PlotOrientation.HORIZONTAL(水平)
參數6:boolean legend —— 設定是否顯示圖例
參數7:boolean tooltips —— 設定是否採用標準生成器
參數8:boolean urls —— 設定是否包生成連接
建立 maven 項目(不使用 maven 的朋友在 myeclipse 建立 Web 項目,或在 eclipse 下建立動態 Web 項目),項目名起: jfreechart-demo
web.xml 配置:
web
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- jfreechart -->
<servlet>
<servlet-name>DisplayChart</servlet-name>
<servlet-class>org.jfree.chart.servlet.DisplayChart</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DisplayChart</servlet-name>
<url-pattern>/DisplayChart</url-pattern>
</servlet-mapping>
<!-- 開啓Struts2監聽 -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>/index.jsp</welcome-file>
</welcome-file-list>
</web-app>
apache
struts.xml 配置(這裏使用了 Struts2 的 convention 插件來實現零配置,沒有使用 convention 插件的朋友請自行配置相應的 action):
api
<?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>
<constant name="struts.devMode" value="true"/> <!-- 開發模式 -->
<constant name="struts.i18n.encoding" value="UTF-8"/> <!-- Web運用編碼 -->
<constant name="struts.convention.result.path" value="/view/" /> <!-- 結果資源的路徑 -->
<constant name="struts.convention.action.name.separator" value="_" /> <!-- URL資源分隔符 -->
<constant name="struts.convention.classes.reload" value="true" /> <!-- convention類從新加載 -->
<constant name="struts.action.extension" value="action,do,html" /> <!-- 請求後綴 -->
</struts>
session
pom.xml 配置(不使用 maven 的朋友不用配置這個文件,直接將須要的 jar 包導進項目便可):
app
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.fancy</groupId>
<artifactId>jfreechart-demo</artifactId>
<packaging>war</packaging>
<version>1.0</version>
<name>jfreechart-demo Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<struts.version>2.1.8</struts.version>
</properties>
<dependencies>
<!-- Struts2 framework -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>${struts.version}</version>
</dependency>
<!-- Struts2 convention -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-convention-plugin</artifactId>
<version>${struts.version}</version>
</dependency>
<!-- servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<!-- JFreeChart -->
<dependency>
<groupId>jfree</groupId>
<artifactId>jfreechart</artifactId>
<version>1.0.9</version>
</dependency>
</dependencies>
<build>
<finalName>jfreechar-demo</finalName>
<!-- Jetty Server -->
<plugins>
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>maven-jetty-plugin</artifactId>
<version>6.1.10</version>
<configuration>
<scanIntervalSeconds>2</scanIntervalSeconds>
</configuration>
</plugin>
</plugins>
</build>
</project>
eclipse
package com.fancy.action;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.SessionAware;
import com.opensymphony.xwork2.ActionSupport;
/**
* -----------------------------------------
* @描述 Action 超類
* @做者 fancy
* @郵箱 fancydeepin@yeah.net
* @日期 2012-8-6 <p>
* -----------------------------------------
*/
public class BaseAction extends ActionSupport implements SessionAware{
private static final long serialVersionUID = 1L;
protected Map<String, Object> session; //session
public void setSession(Map<String, Object> session) {
this.session = session;
}
public HttpSession getHttpSession() {
HttpServletRequest request = ServletActionContext.getRequest();
return request.getSession();
}
}
webapp
(核心類,主要看這裏就行,你能夠將 execute 方法裏面的代碼直接拷貝到 jsp 上面作測試)
jsp
package com.fancy.action;
import java.awt.Color;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.servlet.ServletUtilities;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.general.DatasetUtilities;
/**
* -----------------------------------------
* @描述 柱狀圖
* @做者 fancy
* @郵箱 fancydeepin@yeah.net
* @日期 2012-8-6 <p>
* -----------------------------------------
*/
public class CylinderAction extends BaseAction{
private static final long serialVersionUID = 1L;
private String fileName;
public String execute() throws Exception{
//模擬數據
double[][] data = {{1185,995,1286,1210},{916,1028,900,885},{982,763,935,665},{384,568,928,773}};
String[] rowKeys = {"A產品","B產品","C產品","D產品"};
String[] columKeys = {"E-1區","E-2區","E-3區","E-4區"};
//建立Dataset對象
CategoryDataset dataset = DatasetUtilities.createCategoryDataset(rowKeys, columKeys, data);
//建立3D柱狀圖
JFreeChart chart = ChartFactory.createBarChart3D("2011年產品銷售量", "", "銷量/件", dataset, PlotOrientation.VERTICAL, true, true, false);
//設置背景顏色
chart.setBackgroundPaint(Color.WHITE);
fileName = ServletUtilities.saveChartAsPNG(chart, 700, 400, null, getHttpSession());
return "cylinder";
}
public String getFileName() {
return fileName;
}
}
在 webapp 目錄下建立 view 子目錄,在 view 目錄裏建立 cylinder.jsp 文件(不使用 maven 的朋友 jsp 文件位置請自行對應)
cylinder.jsp 文件:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>柱狀圖</title>
</head>
<body>
<img src="${pageContext.request.contextPath}/DisplayChart?filename=${fileName}" border=0 usemap="#${fileName}">
</body>
</html>
訪問:http://localhost:8080/jfreechart-demo/cylinder.html (沒有使用 convention 插件的朋友,訪問地址請自行對應)結果如圖:
在上圖中,能夠大概的看出產品的銷售量在哪一個範圍以內,可是並無具體的數值,下面經過在 CylinderAction 類上添加代碼來使得這些數值可以被顯示:
package com.fancy.action;
import java.awt.Color;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.labels.ItemLabelAnchor;
import org.jfree.chart.labels.ItemLabelPosition;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer3D;
import org.jfree.chart.servlet.ServletUtilities;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.general.DatasetUtilities;
import org.jfree.ui.TextAnchor;
/**
* -----------------------------------------
* @描述 柱狀圖
* @做者 fancy
* @郵箱 fancydeepin@yeah.net
* @日期 2012-8-6 <p>
* -----------------------------------------
*/
public class CylinderAction extends BaseAction{
private static final long serialVersionUID = 1L;
private String fileName;
public String execute() throws Exception{
//模擬數據
double[][] data = {{1185,995,1286,1210},{916,1028,900,885},{982,763,935,665},{384,568,928,773}};
String[] rowKeys = {"A產品","B產品","C產品","D產品"};
String[] columKeys = {"E-1區","E-2區","E-3區","E-4區"};
//建立Dataset對象
CategoryDataset dataset = DatasetUtilities.createCategoryDataset(rowKeys, columKeys, data);
//建立3D柱狀圖
JFreeChart chart = ChartFactory.createBarChart3D("2011年產品銷售量", "", "銷量/件", dataset, PlotOrientation.VERTICAL, true, true, false);
//設置背景顏色
chart.setBackgroundPaint(Color.WHITE);
//建立柱體繪製器對象
BarRenderer3D renderer = new BarRenderer3D();
renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
//設置柱體數值可見
renderer.setBaseItemLabelsVisible(true);
//調整數值顯示位置
renderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT));
renderer.setItemLabelAnchorOffset(10D);
chart.getCategoryPlot().setRenderer(renderer);
fileName = ServletUtilities.saveChartAsPNG(chart, 700, 400, null, getHttpSession());
return "cylinder";
}
public String getFileName() {
return fileName;
}
}
再次訪問:http://localhost:8080/jfreechart-demo/cylinder.html 結果如圖: