一:下載需要的2個jar文件
jcommon-版本號.jar,jfreechart-版本號.jar,注意版本不要太高。
實例一:比較簡單的application版本的餅圖
1 /** 2 * 3 */ 4 package com.hlcui.jfreechart; 5 6 import java.awt.Font; 7 8 import org.jfree.chart.ChartFactory; 9 import org.jfree.chart.ChartFrame; 10 import org.jfree.chart.JFreeChart; 11 import org.jfree.chart.StandardChartTheme; 12 import org.jfree.data.general.DefaultPieDataset; 13 14 /** 15 * @author Administrator 16 * 17 */ 18 public class JfreeChartTest { 19 public static void main(String[] args) { 20 generatePieChart(); 21 } 22 23 // 畫餅圖 24 public static void generatePieChart() { 25 DefaultPieDataset dpd = new DefaultPieDataset(); // 建立一個默認的餅圖 26 dpd.setValue("管理人員", 25); // 輸入數據 27 dpd.setValue("市場人員", 25); 28 dpd.setValue("開發人員", 45); 29 dpd.setValue("其他人員", 10); 30 31 // 創建主題樣式 (可以解決中文亂碼問題) 32 StandardChartTheme standardChartTheme = new StandardChartTheme("CN"); 33 // 設置標題字體 34 standardChartTheme.setExtraLargeFont(new Font("隸書", Font.BOLD, 20)); 35 // 設置圖例的字體 36 standardChartTheme.setRegularFont(new Font("宋書", Font.PLAIN, 15)); 37 // 設置軸向的字體 38 standardChartTheme.setLargeFont(new Font("宋書", Font.PLAIN, 15)); 39 // 應用主題樣式 40 ChartFactory.setChartTheme(standardChartTheme); 41 42 JFreeChart chart = ChartFactory.createPieChart("某公司人員組織數據圖", dpd, true, 43 true, false); 44 // 可以查具體的API文檔,第一個參數是標題,第二個參數是一個數據集,第三個參數表示是否顯示Legend,第四個參數表示是否顯示提示,第五個參數表示圖中是否存在URL 45 ChartFrame chartFrame = new ChartFrame("某公司人員組織數據圖", chart); 46 // chart要放在Java容器組件中,ChartFrame繼承自java的Jframe類。該第一個參數的數據是放在窗口左上角的,不是正中間的標題。 47 chartFrame.pack(); // 以合適的大小展現圖形 48 chartFrame.setVisible(true);// 圖形是否可見 49 } 50 }
運行結果:
注:一個圖表由以上3個部分組成:
實例二:一個結構更加明晰的application版本的柱狀圖,將邏輯分裝到各個函數中去。
package com.test.jfreechart;
import java.awt.Font;
import javax.swing.JPanel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.ui.ApplicationFrame;
public class JFreeChartTest2 extends ApplicationFrame
{
public JFreeChartTest2(String title)
{
super(title);
this.setContentPane(createPanel()); //構造函數中自動創建Java的panel面板
}
public static CategoryDataset createDataset() //創建柱狀圖數據集
{
DefaultCategoryDataset dataset=new DefaultCategoryDataset();
dataset.setValue(10,"a","管理人員");
dataset.setValue(20,"b","市場人員");
dataset.setValue(40,"c","開發人員");
dataset.setValue(15,"d","其他人員");
return dataset;
}
public static JFreeChart createChart(CategoryDataset dataset) //用數據集創建一個圖表
{
JFreeChart chart=ChartFactory.createBarChart("hi", "人員分布",
"人員數量", dataset, PlotOrientation.VERTICAL, true, true, false); //創建一個JFreeChart
chart.setTitle(new TextTitle("某公司組織結構圖",new Font("宋體",Font.BOLD+Font.ITALIC,20)));//可以重新設置標題,替換“hi”標題
CategoryPlot plot=(CategoryPlot)chart.getPlot();//獲得圖標中間部分,即plot
CategoryAxis categoryAxis=plot.getDomainAxis();//獲得橫坐標
categoryAxis.setLabelFont(new Font("微軟雅黑",Font.BOLD,12));//設置橫坐標字體
return chart;
}
public static JPanel createPanel()
{
JFreeChart chart =createChart(createDataset());
return new ChartPanel(chart); //將chart對象放入Panel面板中去,ChartPanel類已繼承Jpanel
}
public static void main(String[] args)
{
JFreeChartTest2 chart=new JFreeChartTest2("某公司組織結構圖");
chart.pack();//以合適的大小顯示
chart.setVisible(true);
}
}
運行結果如下:
實例三:將chart圖表轉換成JPEG格式的圖片的application
package com.test.jfreechart;
import java.awt.Font;
import java.io.FileOutputStream;
import java.io.OutputStream;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.title.LegendTitle;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.general.DefaultPieDataset;
public class JFreeChartTest3
{
public static void main(String[] args) throws Exception
{
JFreeChart chart=ChartFactory.createPieChart("某公司人員組織數據圖",getDataset(),true,true,false);
chart.setTitle(new TextTitle("某公司組織結構圖",new Font("宋體",Font.BOLD+Font.ITALIC,20)));
LegendTitle legend=chart.getLegend(0);//設置Legend
legend.setItemFont(new Font("宋體",Font.BOLD,14));
PiePlot plot=(PiePlot) chart.getPlot();//設置Plot
plot.setLabelFont(new Font("隸書",Font.BOLD,16));
OutputStream os = new FileOutputStream("company.jpeg");//圖片是文件格式的,故要用到FileOutputStream用來輸出。
ChartUtilities.writeChartAsJPEG(os, chart, 1000, 800);
//使用一個面向application的工具類,將chart轉換成JPEG格式的圖片。第3個參數是寬度,第4個參數是高度。
os.close();//關閉輸出流
}
private static DefaultPieDataset getDataset()
{
DefaultPieDataset dpd=new DefaultPieDataset(); //建立一個默認的餅圖
dpd.setValue("管理人員", 25); //輸入數據
dpd.setValue("市場人員", 25);
dpd.setValue("開發人員", 45);
dpd.setValue("其他人員", 10);
return dpd;
}
}
運行結果如下,在該項目的根目錄下生成了JPEG格式的圖片,注意不是在webroot目錄下。
實例四:將類似實例三生成的圖片嵌入到JSP頁面中去。
1.web.xml中加入以下配置信息.
<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>
2.jfreeChart.jsp
<%@ page language="java" contentType="text/html; charset=GB18030"
pageEncoding="GB18030"%>
<%@ page import="org.jfree.data.general.DefaultPieDataset,org.jfree.chart.ChartFactory
,org.jfree.chart.JFreeChart,org.jfree.chart.servlet.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>Insert title here</title>
</head>
<body>
<%
DefaultPieDataset dpd = new DefaultPieDataset();
dpd.setValue("管理人員", 25);
dpd.setValue("市場人員", 25);
dpd.setValue("開發人員", 45);
dpd.setValue("其他人員", 10);
JFreeChart chart = ChartFactory.createPieChart("某公司組織結構圖",dpd, true, false, false);
String fileName = ServletUtilities.saveChartAsPNG(chart,800,600,session);
//ServletUtilities是面向web開發的工具類,返回一個字符串文件名,文件名自動生成,生成好的圖片會自動放在服務器(tomcat)的臨時文件下(temp)
String url = request.getContextPath() + "/DisplayChart?filename=" + fileName;
//根據文件名去臨時目錄下尋找該圖片,這里的/DisplayChart路徑要與配置文件里用戶自定義的<url-pattern>一致
%>
<img src="<%= url %>" width="800" height="600">
</body>
</html>
顯示結果為:
實例五:模擬對運動項目投票然后查看投票JFreeChart圖表
原理:服務器不重啟時,session結果依然保存模擬投票功能,使用struts2-jfreechart-plugin-版本號.jar插件將圖表對象在action中自動渲染。
注意:不要忘記添加struts2-jfreechart-plugin-版本號.jar到工程中。
1.Action類:
package com.test.action;
import java.awt.Font;
import java.util.List;
import java.util.Map;
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.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class ViewResultAction extends ActionSupport
{
private JFreeChart chart;//這里變量名必須是chart,不能是其他變量名
private List<String> interest; //struts會自動類型轉換,將頁面傳遞過來的值存到List中去
public JFreeChart getChart()//getChart()方法是必須的,setChart()可以不寫.
{ //在action中的chart屬性的get方法中,創建chart對象,然后進行設置plot主體和顏色;以及legend顏色和字體
chart = ChartFactory.createBarChart("興趣統計結果", "項目", "結果", this
.getDataset(), PlotOrientation.VERTICAL, false, false, false);
chart.setTitle(new TextTitle("興趣統計結果",new Font("黑體",Font.BOLD,22)));
CategoryPlot plot = (CategoryPlot)chart.getPlot();
CategoryAxis categoryAxis = plot.getDomainAxis();
categoryAxis.setLabelFont(new Font("宋體",Font.BOLD,22));
categoryAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);//設置角度
NumberAxis numberAxis = (NumberAxis)plot.getRangeAxis();
numberAxis.setLabelFont(new Font("宋體",Font.BOLD,22));
return chart;
}
public List<String> getInterest()
{
return interest;
}
public void setInterest(List<String> interest)
{
this.interest = interest;
}
@Override
public String execute() throws Exception
{
return SUCCESS;
}
@SuppressWarnings("unchecked")
private void increaseResult(List<String> list)//真正在開發中是不會寫在action里的,應該寫在model中
{ //模擬一個臨時數據庫
ActionContext context = ActionContext.getContext();//struts與servlet的耦合方式一
Map map = context.getApplication();
for (String str : list)
{
if (null == map.get(str))//表示用戶第一次投票
{
map.put(str, 1);
}
else
{
map.put(str, (Integer) map.get(str) + 1);
}
}
}
@SuppressWarnings("unchecked")
private CategoryDataset getDataset() //得到數據集。
{
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
this.increaseResult(this.getInterest());
ActionContext context = ActionContext.getContext();
Map map = context.getApplication();
dataset.setValue((Integer) map.get("football"), "", "足球");//更新成最新值
dataset.setValue((Integer) map.get("basketball"), "", "籃球");
dataset.setValue((Integer) map.get("volleyball"), "", "排球");
dataset.setValue((Integer) map.get("badminton"), "", "羽毛球");
return dataset;
}
}
2.Jsp頁面
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
</head>
<body>
<h1><font color="blue">請選擇喜歡的運動項目</font></h1>
<s:form action="viewResult">
<s:checkbox name="interest" label="足球" fieldValue="football"></s:checkbox>
<s:checkbox name="interest" label="籃球" fieldValue="basketball"></s:checkbox>
<s:checkbox name="interest" label="排球" fieldValue="volleyball"></s:checkbox>
<s:checkbox name="interest" label="羽毛球" fieldValue="badminton"></s:checkbox>
<!--
<s:checkboxlist list="#{'computer':'計算機','math':'數學'}" name="interest" label="課程" labelposition="top"></s:checkboxlist>
-->
<s:submit value="提交"></s:submit>
</s:form>
</body>
</html>
3.struts.xml的配置
<package name="struts2" extends="struts-default,jfreechart-default">
注意:這里的包要繼承2個。網上常用的方法是將struts2-jfreechart-plugin-版本號.jar插件解壓,然后修改struts-plugin-xml中package,讓它繼承於struts-default包然后重新打包,再配置action中的package包,使其extends= jfreechart-default,感覺這種做法比較麻煩。還是直接繼承2個包比較方便。
<action name="viewResult" class="com.test.action.ViewResultAction">
<result name="success" type="chart">
<param name="height">600</param>
<param name="width">800</param>
</result>
</action>
這里<result/>標簽中不需要再加入JSP頁面用來跳轉,會直接跳轉到由chart所指定的ChartResult類來處理。
附struts-plugin-xml文件內容:
<struts>
<package name="jfreechart-default">
<result-types>
<result-type name="chart" class="org.apache.struts2.dispatcher.ChartResult">
<param name="height">150</param>
<param name="width">200</param>
</result-type>
</result-types>
</package>
</struts>
最后頁面顯示結果:
轉載:http://www.cnblogs.com/xingyun/archive/2012/02/05/2339237.html