`
xiejin2008
  • 浏览: 123681 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Ext3.0 动态数据 Chart 初探

阅读更多

学习了Ext的Chart,看了官方提供的Example,也搜索了些资料。整理出了一份Ext Chart定时动态获取后台的Json数据的Demo。

参考的不错的文章有:

第一篇文章:http://atian25.iteye.com/blog/413947

这个有用的:关于Chart的一些样式和具体配置的用法参数:http://developer.yahoo.com/yui/charts/

Yahoo:  http://developer.yahoo.com/flash/astra-flash/

http://www.hmgis.cn/post/366.html

发现ExtJs Chart的一个Bug:            http://blog.csdn.net/acsu/archive/2009/11/26/4881834.aspx

如何自定义 ExtJS.chart.PieChart 各分块的颜色

http://www.cnblogs.com/beginor/archive/2009/11/22/1608034.html

 

 

Demo整体思路:

Servlert将List封装了JavaBean对象,JavaBean对象中的属性数据随机产生,然后通过Json-lib将List转换成json格式字符串,并且打印。

然后页面Js通过Ext.data.JsonReader ,Ext.data.Store 读取返回的json格式数据。

 

工程目录图:

 

 

Src目录:DataBean.java ,一个简单的JavaBean类。

            DataServert.java 一个产生数据的Servlet 类(返回Json格式数据)。

 

 

WebRoot目录:chart 中,charts.js  关键的js代码。

                        extjs目录, ext中通用的js,css,swf等资源文件。

 

效果图片:

 

 

关键代码:

javaBean:

package com.bean;

import java.io.Serializable;

public class DataBean implements Serializable {
    
    private static final long serialVersionUID = 1L;
    
    private String            name             = "";
    private int               visits           = 0;
    private int               views            = 0;
    
    public DataBean (String name, int visits, int views) {
        this.name = name;
        this.views = views;
        this.visits = visits;
    }
    
    public DataBean(){}
    
    public String getName () {
        return name;
    }
    
    public void setName ( String name ) {
        this.name = name;
    }
    
    public int getVisits () {
        return visits;
    }
    
    public void setVisits ( int visits ) {
        this.visits = visits;
    }
    
    public int getViews () {
        return views;
    }
    
    public void setViews ( int views ) {
        this.views = views;
    }
}

 

DataServert:

package com.bean;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

public class DataServert extends HttpServlet {
    
    /**
    	 * Constructor of the object.
    	 */
    public DataServert () {
        super ();
    }
    
    /**
    	 * Destruction of the servlet. <br>
    	 */
    public void destroy () {
        super.destroy (); // Just puts "destroy" string in log
        // Put your code here
    }
    
    /**
    	 * The doGet method of the servlet. <br>
    	 *
    	 * This method is called when a form has its tag value method equals to get.
    	 * 
    	 * @param request the request send by the client to the server
    	 * @param response the response send by the server to the client
    	 * @throws ServletException if an error occurred
    	 * @throws IOException if an error occurred
    	 */
    public void doGet ( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
        response.setContentType ( "text/html;charset=utf-8" );
        request.setCharacterEncoding ( "utf-8" );
        PrintWriter out = response.getWriter ();
        String jsonString = "";
        List<DataBean> list = new ArrayList<DataBean> ();
        String[] names = { "1G", "2G", "3G", "4G", "5G", "6G", "7G", "8G" };
        Random random = new Random ();
        for (int i = 0; i < names.length; i++) {
            int num = random.nextInt ( 100 ) * 100;
            DataBean data = new DataBean ( names[i], num, num / 2 );
            list.add ( data );
        }
        JSONArray arryData = null;
        arryData = JSONArray.fromObject ( list );
        jsonString = "{totalCount:" + list.size () + ",data:" + arryData.toString ().replaceAll ( "\n", "" ) + "}";
        System.out.println (jsonString); 
        out.print ( jsonString ); 
        out.flush ();
        out.close ();
    }
    
    /**
    	 * The doPost method of the servlet. <br>
    	 *
    	 * This method is called when a form has its tag value method equals to post.
    	 * 
    	 * @param request the request send by the client to the server
    	 * @param response the response send by the server to the client
    	 * @throws ServletException if an error occurred
    	 * @throws IOException if an error occurred
    	 */
    public void doPost ( HttpServletRequest request, HttpServletResponse response ) throws ServletException,
            IOException {
        doGet ( request, response );
        
    }
    
    /**
    	 * Initialization of the servlet. <br>
    	 *
    	 * @throws ServletException if an error occurs
    	 */
    public void init () throws ServletException {
        // Put your code here
    }
    
}

 

charts.js

 

Ext.chart.Chart.CHART_URL = '../extjs/resources/charts.swf'; // 模板flash
var json_store;
Ext.onReady(function() {
			var json_reader = new Ext.data.JsonReader({
						idProperty : "name",
			root : 'data',
			totalProperty : "totalCount",
			fields : [{
						name : 'name',
						type : "string"
					}, {
						name : 'views',
						type : "int"
					}, {
						name : 'visits',
						type : "int"
					}]
		});

json_store = new Ext.data.Store({
			proxy : new Ext.data.HttpProxy({
						url : '../DataServert.do',
						method : 'POST'
					}),
			reader : json_reader
		});

// extra extra simple
new Ext.Panel({
			title : 'ExtJS.com Visits Trend, 2007/2008 ',
			renderTo : 'container',
			width : 500,
			height : 300,
			layout : 'fit',

			items : {
				xtype : 'linechart', // 类型
				store : json_store,
				xField : 'name', // X轴取值
				yField : 'visits', // Y轴取值
				listeners : {
					itemclick : function(o) {// 点击事件.
						var rec = store.getAt(o.index);
						Ext.example.msg('被选中项:', '你选择了 {0}.', rec
										.get('name'));
					}
				},
				series : [{
							type : 'line', // line
							displayName : '点击数',
							yField : 'visits',
							style : {
								color : '#6666CC'
							}
						}]
			}
		});

// extra simple
new Ext.Panel({
			iconCls : 'chart',
			title : 'ExtJS.com Visits Trend, 2007/2008 (简单样式)',
			frame : true,
			renderTo : 'container',
			width : 500,
			height : 300,
			layout : 'fit',

			items : {
				xtype : 'columnchart',
				store : json_store,
				url : '../extjs/resources/charts.swf',
				xField : 'name',
				yField : 'visits',
				yAxis : new Ext.chart.NumericAxis({
							displayName : 'Visits',
							labelRenderer : Ext.util.Format
									.numberRenderer('0,0')
						}),
				tipRenderer : function(chart, record) {
					return Ext.util.Format.number(
							record.data.visits, '0,0')
							+ ' visits in ' + record.data.name;
				},
				chartStyle : {
					animationEnabled : true,// 是否支持动态数据变化
					legend : {// 图例
						display : "bottom",
						spacing : 2,
						padding : 5,
						font : {
							name : 'Tahoma',
							color : '#3366FF',
							size : 12,
							bold : true
						}
					}
				},
				series : [{
							type : 'column', // line
							displayName : '点击数',
							yField : 'visits',
							style : {
								color : '#3366FF'
							}
						}]
			}
		});

// more complex with a custom look
new Ext.Panel({
			iconCls : 'chart',// 样式
			title : 'ExtJS.com Visits and Pageviews, 2007/2008  (复杂样式)',
			frame : true,
			renderTo : 'container',
			width : 500,
			height : 300,
			layout : 'fit',

			items : {
				xtype : 'columnchart',// 柱状图
				store : json_store,
				url : '../extjs/resources/charts.swf',
				xField : 'name',// X轴显示的值
				yAxis : new Ext.chart.NumericAxis({
							displayName : 'Visits',
							labelRenderer : Ext.util.Format
									.numberRenderer('0,0')
						}), // Y 轴显示的值
				tipRenderer : function(chart, record, index, series) {// tip渲染
					if (series.yField == 'visits') {
						return Ext.util.Format.number(
								record.data.visits, '0,0')
								+ ' visits in ' + record.data.name;
					} else {
						return Ext.util.Format.number(
								record.data.views, '0,0')
								+ ' page views in '
								+ record.data.name;
					}
				},
				chartStyle : {
					padding : 10,
					animationEnabled : true,// 是否支持动态数据变化
					font : {// 图表整体字体
						name : 'Tahoma',
						color : 'silver',
						size : 11
					},
					border : {
                    // color:'#3399FF',
					// size:1
					},
					background : {
						color : '#CCCCCC',// 背景颜色
						alpha : 0.1
						// 透明度
						// image:
						// mode:stretch
					},
					legend : {// 图例
						display : "bottom",
						spacing : 2,
						padding : 5,
						font : {
							name : 'Tahoma',
							color : '#3366FF',
							size : 12,
							bold : true
						}
					},
					dataTip : { // 鼠标经过,数据提示样式
						padding : 5,// 提示内容与边框的距离
						border : {
							color : "#FF3333",
							size : 1
						},
						background : {
							color : 0xDAE7F6,// 背景颜色透明度
							alpha : .8
							// 背景颜色透明度
						},
						font : {
							name : 'Tahoma',
							color : '#FF3300',
							size : 10,
							bold : true
						}
					},
					xAxis : { // X 轴
						color : 0x69aBc8, // X轴颜色
						majorTicks : {// 大刻度值
							color : 0x69aBc8,
							length : 4
						},
						minorTicks : {// 小刻度值
							color : 0x69aBc8,
							length : 2
						},
						majorGridLines : {
							size : 1,
							color : '#999999'
						},
						// showLabels:false,
						labelDistance : 4
					},
					yAxis : {
						color : 0x69aBc8,
						majorTicks : {// 大刻度值
							color : 0x69aBc8,
							length : 4
						},
						minorTicks : {// 小刻度值
							color : 0x69aBc8,
							length : 2
						},
						majorGridLines : {
							size : 1,
							color : '#999999'
						}
					}
				},
				series : [{
							type : 'column',// 柱状图
							displayName : '浏览数',
							yField : 'views',
							style : {
								// image : 'bar.gif',
								// mode : 'stretch',
								color : '#66CCFF'
							}
						}, {
							type : 'column', // line
							displayName : '点击数',
							yField : 'visits',
							style : {
								color : '#FF3300'
								// lineAlpha:0.5,
								// lineColor:'#FF3300',
								// alpha:0.8,
								// size:10
							}
						}]
			}
		});

// a new example
new Ext.Panel({
			width : 500,
			height : 300,
			renderTo : 'container',
			title : 'Stacked Bar Chart',
			items : {
				xtype : 'stackedbarchart',// 图表类型
				store : json_store,
				yField : 'name',
				xAxis : new Ext.chart.NumericAxis({
					stackingEnabled : true,
					labelRenderer : Ext.util.Format.usMoney
						// 格式化渲染
					}),
				chartStyle : {
					legend : {// 图例
						display : "top",
						spacing : 2,
						padding : 5,
						font : {
							name : 'Tahoma',
							color : '#3366FF',
							size : 12,
							bold : true
						}
					},
					dataTip : { // 鼠标经过,数据提示样式
						padding : 5,// 提示内容与边框的距离
						border : {
							color : "#FF3333",
							size : 1
						},
						background : {
							color : 0xDAE7F6,// 背景颜色透明度
							alpha : .8
							// 背景颜色透明度
						},
						font : {
							name : 'Tahoma',
							color : '#FF3300',
							size : 10,
							bold : true
						}
					}
				},
				series : [{
							xField : 'views',
							displayName : '访问量'
						}, {
							xField : 'visits',
							displayName : '点击量'
						}]
			}
		});

// a Pie Chart example
new Ext.Panel({
			width : 400,
			height : 400,
			title : 'Pie Chart with Legend',
			renderTo : 'container',
			items : {
				store : json_store,
				xtype : 'piechart',// 餅圖
				dataField : 'views',// 数据
				categoryField : 'name',// 项目
				// extra styles get applied to the chart defaults
				extraStyle : {
					legend : // 图例
					{
						display : 'bottom',
						padding : 5,
						font : {
							family : 'Tahoma',
										size : 13
									}
								}
							}
						}
					});

			loadData();
		});
function loadData() {
	json_store.reload();
	setTimeout('loadData();', 1000);
}

 

Charts.jsp

 

 

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
    String path = request.getContextPath ();
    String basePath = request.getScheme () + "://" + request.getServerName () + ":" + request.getServerPort ()
            + path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>  
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<title>Charts</title>
		<link rel="stylesheet" type="text/css"
			href="../extjs/resources/css/ext-all.css" />

		<!-- GC -->
		<!-- LIBS -->
		<script type="text/javascript" src="../extjs/adapter/ext/ext-base.js"></script>
		<!-- ENDLIBS -->

		<script type="text/javascript" src="../extjs/ext-all.js"></script>

		<script type="text/javascript" src="charts.js"></script>

		<!-- Common Styles for the examples -->
		<link rel="stylesheet" type="text/css"
			href="../extjs/shared/examples.css" />

		<style type="text/css">
#container {
	padding: 10px;
}

#container .x-panel {
	margin: 10px;
}

#container .x-panel-ml {
	padding-left: 1px;
}

#container .x-panel-mr {
	padding-right: 1px;
}

#container .x-panel-bl {
	padding-left: 2px;
}

#container .x-panel-br {
	padding-right: 2px;
}

#container .x-panel-body {
	
}

#container .x-panel-mc {
	padding-top: 0;
}

#container .x-panel-bc .x-panel-footer {
	padding-bottom: 2px;
}

#container .x-panel-nofooter .x-panel-bc {
	height: 2px;
}

#container .x-toolbar {
	border: 1px solid #99BBE8;
	border-width: 0 0 1px 0;
}

.chart {
	background-image: url(chart.gif) !important;
}
</style>
	</head>
	<body>
		<script type="text/javascript" src="../extjs/shared/examples.js"></script>
		<!-- EXAMPLES -->
		<h1>
			Charts
		</h1>
		

		<div id="container">

		</div>

	</body>
</html>

 

下面附上源码:

 

13
0
分享到:
评论
9 楼 wang1248912822 2013-08-07  
[size=large][/size] [b]        [/b]
8 楼 fushun_test 2012-11-30  
很不错,柱状的每个珠子颜色和饼状的每个部分的颜色可以自定义吗
7 楼 yaniel8931 2012-08-01  
请教下,如果想让X轴上的文字,斜着显示如何设置?急
6 楼 ycwycf1 2012-07-25  
5 楼 guoyuan 2011-11-23  
4 楼 xiejin2008 2011-11-01  
zxm94w 写道
楼主你好,谢谢你的Demo,学习很多。
想问几个问题:
1、如何将X轴定义为时间轴?
2、如果我的X轴是时间轴,如何将后台传得数据(比如时间是个字符串格式的)格式化成YYYY-MM-DD的格式


谢谢!
呵呵,我还得研究研究,好久没用它了。
3 楼 zxm94w 2011-10-25  
楼主你好,谢谢你的Demo,学习很多。
想问几个问题:
1、如何将X轴定义为时间轴?
2、如果我的X轴是时间轴,如何将后台传得数据(比如时间是个字符串格式的)格式化成YYYY-MM-DD的格式


谢谢!
2 楼 xiejin2008 2010-09-24  
可以的.下次帮你实验一下
1 楼 highbbs 2010-09-15  
问个问题,对于柱状图,每根柱子的颜色可以动态定义吗?

相关推荐

Global site tag (gtag.js) - Google Analytics