当前位置: 代码迷 >> JavaScript >> ExtJS课题-表格面板 (转)
  详细解决方案

ExtJS课题-表格面板 (转)

热度:1401   发布时间:2012-11-23 22:54:33.0
ExtJS专题-表格面板 (转)
ExtJS中的表格功能非常强大,包括了排序、缓存、拖动、隐藏某一列、自动显示行号、列汇总、单元格编辑等实用功能。但很多人在应用的时候都会因为遇到一些细节问题而苦恼,为什么提示信息出不来呀?为什么s.gif图片在断网的情况下不能显示啊?为什么从后台得不到JSON数据啊?为什么日期的格式无法转换啊?为什么翻页就是报错啊?为什么拖曳功能就是实现不了啊?等等等等。最后归结到一句话,为什么ExtJS这么乱七八糟啊?!呵呵,为了帮助大家解决ExtJS的这些小麻烦,许老师做了下面的一个小DEMO来演示GridPanel的用法,后面有时间会陆陆续续演示其它组件的主要用法。我的愿望就是大家看了这个小专题之后,能够在最短的时间内掌握ExtJS的各种组件的应用。至于基本功的修炼,还得烦劳大伙自己用心。好啦,不多说,下面我们来看ExtJS中最实用的组件:表格面板。

表格由类Ext.grid.GridPanel定义,继承自Panel,其xtype为grid。ExtJS中,表格Grid必须包含列定义信息,并指定表格的数据存储器Store。表格的列信息由类Ext.grid.ColumnModel定义、而表格的数据存储器由Ext.data.Store定义。这些都是基础知识,大家应该清楚了。我们主要要牢记,ExtJS里最主要的是JSON数据格式,ColumnModel是要显示表格的列的定义信息,而Store则是数据记录的来源。那么,数据呢,又可以分为本地数据和远程数据,它们分别使用不一样的代理;数据格式有Array,JSON,XML,针对每种数据格式ExtJS都有相应的解析方式,就是Store的读取器。我们最核心的当然是先掌握远程JSON数据的Store的用法。我们来看一个例子,这个例子包含了一般表格的常用功能,譬如按要求改变列的数据,右键菜单,面板折叠,强大的拖曳(drag/drop)以及分页处理。

这里涉及到三个文件,包括前台的grid.html,grid.js和后台的resJson.jsp,我们来分别瞧瞧:
(1)        grid.html,这里要说明的是DOCTYPE不能设置错误,否则IE6.0会显示不出表头的列名。还有就是要汉化提示信息,注意导入ext-lang-zh_CN.js

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css"  href="resources/css/ext-all.css">
<script type="text/javascript" src="resources/js/ext-base.js"></script>
<script type="text/javascript" src="resources/js/ext-all.js"></script>
<script type="text/javascript" src="resources/js/ext-lang-zh_CN.js"></script>
<script type="text/javascript" src="resources/js/grid.js"></script>
<style type="text/css">
</style>
</head>
<body>
<div id="myGrid"></div>
</body>
</html>

(2)        grid.js,我们的主要功能就在这个JS里面,里面我都做了详细的注释,大家可以对照着学习。

Ext.onReady(function() {
                     Ext.QuickTips.init();// 浮动信息提示
                     Ext.BLANK_IMAGE_URL = 'resources/images/default/s.gif';// 替换图片文件地址为本地
                     // 定义数据源为远程代理和JSON数据格式
                     var ds = new Ext.data.Store({
                                          // proxy: new Ext.data.MemoryProxy(jsondata),
                                          proxy : new Ext.data.HttpProxy({
                                                               url : 'resJson.jsp'
                                                        }),
                                          reader : new Ext.data.JsonReader({
                                                               totalProperty : 'totalProperty',
                                                               root : 'root'
                                                        }, [{
                                                                             name : 'id'
                                                                      }, {
                                                                             name : 'name'
                                                                      }, {
                                                                             name : 'sex'
                                                                      }, {
                                                                             name : "birthday",
                                                                             type : "date",
                                                                             dateFormat : "Y-n-j"
                                                                      }, {
                                                                             name : 'email'
                                                                      }])
                                   });
                     // 加载首页数据,每页显示10条记录
                     ds.load({
                                          params : {
                                                 start : 0,
                                                 limit : 6
                                          }
                                   });
                     // 定义复选框
                     var sm = new Ext.grid.CheckboxSelectionModel();
                     // 定义列模型
                     var cm = new Ext.grid.ColumnModel([
                                   // new Ext.grid.RowNumberer(),// 添加自动行号
                                   sm,// 添加复选框
                                   {
                                          header : '学号',
                                          width : 40,
                                          dataIndex : 'id'
                                   }, {
                                          header : '姓名',
                                          dataIndex : 'name'
                                   }, {
                                          header : '性别',
                                          width : 40,
                                          dataIndex : 'sex',
                                          renderer : changeSex
                                          // 红男绿女
                            }     , {
                                          header : '出生日期',
                                          dataIndex : 'birthday',
                                          renderer : Ext.util.Format.dateRenderer('Y年m月d日')
                                          // 格式化日期
                            }     , {
                                          header : '电子邮件',
                                          width : 120,
                                          dataIndex : 'email',
                                          renderer : sendEmail
                                          // 单击启动邮件客户端发送邮件
                            }]);
                     // 设置所有列字段默认排序
                     cm.defaultSortable = true;
                     // 按要求渲染性别的函数
                     function changeSex(value) {
                            if (value == '男') {
                                   return "<span style='color:red;font-weight:bold;'>男</span>";
                            } else {
                                   return "<span style='color:green;font-weight:bold;'>女</span>";
                            }
                     }
                     // 按要求渲染email的函数
                     function sendEmail(value) {
                            return "<a href=mailto:" + value + ">" + value + "</a>";
                     }
                     // 定义一个表格面板
                     var grid = new Ext.grid.GridPanel({
                                          id : 'student-grid',// 设置标识ID,方便以后引用!
                                          title : '学员信息管理',// 标题
                                          renderTo : 'myGrid',// 显示表格的地方
                                          sm : sm,// 复选框
                                          cm : cm,// 列模型
                                          ds : ds,// 数据源
                                          stripeRows : true,// 加上行条纹
                                          loadMask : true,// 加载数据时遮蔽表格
                                          border : true,// 加上边框
                                          frame : true,// 显示天蓝色圆角框
                                          autoHeight : true,// 自动设置高度,这个配置很重要
                                          width : 700,
                                          x : 1,// 设置初始位置横坐标
                                          y : 1,// 设置初始位置纵坐标
                                          // enableDragDrop : true,//容许行的拖曳
                                          collapsible : true, // 面板可以折叠
                                          // titleCollapse : true,// 单击表头任何地方都可以折叠
                                          floating : true,// 设置浮动,能否拖动成功就靠它了,注意设置浮动后它就置顶了
                                          // 实现拖曳效果,参考官方文档
                                          draggable : {
                                                 insertProxy : false,
                                                 onDrag : function(e) {
                                                        var pel = this.proxy.getEl();
                                                        this.x = pel.getLeft(true);
                                                        this.y = pel.getTop(true);

                                                        var s = this.panel.getEl().shadow;// 拖曳中消除原位置的阴影
                                                        if (s) {
                                                               s.realign(this.x, this.y, pel.getWidth(),
                                                                             pel.getHeight());
                                                        }
                                                 },
                                                 endDrag : function(e) {// 拖曳结束后保存位置效果
                                                        this.panel.setPosition(this.x, this.y);
                                                 }
                                          },
                                          // UI视图配置
                                          viewConfig : {
                                                 forceFit : true
                                                 // 强制适应分布宽度
                                          },
                                          // 表格顶部动作或按钮工具栏
                                          tbar : new Ext.Toolbar({
                                                               items : [{
                                                                      id : 'btnAdd',
                                                                      text : "添加",
                                                                      handler : function() {
                                                                             Ext.MessageBox.alert("添加",
                                                                                           "这里处理添加数据的逻辑!");
                                                                      }
                                                               }, new Ext.Toolbar.SplitButton({}), {
                                                                      id : 'btnEdit',
                                                                      text : "编辑",
                                                                      handler : function() {
                                                                             Ext.MessageBox.alert("编辑",
                                                                                           "这里处理编辑数据的逻辑!");
                                                                      }
                                                               }, '-', {
                                                                      id : 'btnDel',
                                                                      text : "删除",
                                                                      handler : function() {
                                                                             Ext.MessageBox.alert("删除",
                                                                                           "这里处理删除数据的逻辑!");
                                                                      }
                                                               }]
                                                        }),

                                          // 表格底部分页工具栏
                                          bbar : new Ext.PagingToolbar({
                                                               pageSize : 6,
                                                               store : ds,
                                                               displayInfo : true,
                                                               displayMsg : '显示第 {0} 条到 {1} 条记录,一共 {2} 条',
                                                               emptyMsg : "没有记录"
                                                        })

                                   });

                     // 给grid动态增加右键事件,rowcontextmenu是事件名,rightClickFn是事件触发的处理函数
                     grid.on('rowcontextmenu', rightClickFn);
                     var rightClickMenu = new Ext.menu.Menu({
                                          id : 'rightClickCont',
                                          items : [{
                                                               id : 'rMenu1',
                                                               handler : rMenu1Fn,// 点击后触发的事件
                                                               text : '右键菜单1'
                                                        }, {
                                                               // id: 'rMenu2',
                                                               // handler: rMenu2Fn,
                                                               text : '右键菜单2'
                                                        }]
                                   });

                     function rightClickFn(grid, rowindex, e) {
                            e.preventDefault();// 阻止浏览器默认右键效果
                            rightClickMenu.showAt(e.getXY());// 在右键点击的地方显示菜单rightClickMenu
                     }
                     function rMenu1Fn() {
                            Ext.MessageBox.alert('right', '您可以自定义右键处理!');// 只是一个示例
                     }

              });

(3)        resJson.jsp,前面只是前台部分,页面的动态数据就要用HTTP协议从后台组件上获取,这样,只要你实现一种能够响应HTTP请求的后台WEB组件即可,你可以写一个Servlet,写一个Struts的Action,或者是一个JSP都行。我们这里方便起见,做的是一个JSP,在这个JSP里使用了json-lib的包.这是一个用Java操作JSON格式数据的工具包,大家可以从网上下载。一般跑过我第一个Extjs应用的人这些包应该都准备好了。我们这里模拟后台实现,并不需要访问数据库,所以很方便。大家要注意的是最后两行代码必须加上,不然服务器传回客户端的就会带上很多与JSON格式无关的HTML标签信息,这样Extjs就无法识别了。

<%@ page language="java" contentType="text/html; charset=UTF-8"
       pageEncoding="UTF-8"
       import="java.util.*,org.leno.javabean.*,net.sf.json.*"%>
<!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=UTF-8">
              <title>Insert title here</title>
       </head>
       <body>
              <%!private static List<Student> list = new ArrayList<Student>();
       static {
              for (int i = 0; i < 100; i++) {
                     Student stu = new Student();
                     stu.setId(i);
                     stu.setName("LENO" + i);
                     if (i % 2 == 0) {
                            stu.setSex('男');
                     } else {
                            stu.setSex('女');
                     }
                     stu.setBirthday("2003-12-11");
                     stu.setEmail("LENO@126.com");
                     list.add(stu);
              }
       }%>
              <%
                     request.setCharacterEncoding("utf-8");
                     response.setCharacterEncoding("utf-8");
                     System.out.println(request.getParameter("name") + " attribute");
                     JSONObject json = new JSONObject();
                     String strStart = request.getParameter("start");
                     String strLimit = request.getParameter("limit");
                     int start = Integer.parseInt(strStart);
                     int limit = Integer.parseInt(strLimit);
                     List<Student> arrList = list.subList(start, start + limit);
                     json.put("totalProperty", 100);
                     JSONArray arr = JSONArray.fromObject(arrList);
                     json.put("root", arr);
                     System.out.println(json);
                     response.getWriter().print(json);
                     out.clear();
                     out = pageContext.pushBody();
              %>
       </body>
</html>

还有一个非常简单的JavaBean这里也给大家贴出来:

package org.leno.javabean;

public class Student {

       private int id;
       private String name;
       private char sex;
       private String birthday;
       private String email;
     
       public int getId() {
              return id;
       }
       public void setId(int id) {
              this.id = id;
       }
       public String getName() {
              return name;
       }
       public void setName(String name) {
              this.name = name;
       }
       public char getSex() {
              return sex;
       }
       public void setSex(char sex) {
              this.sex = sex;
       }
       public String getBirthday() {
              return birthday;
       }
       public void setBirthday(String birthday) {
              this.birthday = birthday;
       }
       public String getEmail() {
              return email;
       }
       public void setEmail(String email) {
              this.email = email;
       }   
}
       怎么样,是不是非常简单?并不多的代码却完成了很多复杂却实用的功能。希望大家能从上面的例子中好好理解ExtJS前台展现的制作和后台交互的方式。这里要强调的是,大家一定要搭建好ExtJS的环境和导入json-lib的相关包,特别是核心的JS,CSS还有图片数据,一定要放在正确的路径。图:
  相关解决方案