有关Flex的DataGrid文章的确不少,都是零零碎碎的,目前还没有发现有个完整的例子供网友参考,这次我花了两天时间做了下Flex关于DataGrid一个指标数据管理系统,当然设计到的mxml会很多,大都是与DataGrid相关,我就抽取最常用的DataGrid的增删改同步数据库及页面数据来讲解
首先整理下思路,首先无论是删除还是修改,必须得获取当前行所在的记录,那么可以设置个全局变量,当DataGrid的itemClick事件出发时将选中的行赋给全局变量
[Bindable]public var acItemsSelected:Object;;
//事件方法
protected function myGrid_itemClickHandler(event:ListEvent):void
{
acItemsSelected = myGrid.selectedItem;
}
这样的话就可以获得了当前选中的对象了
如果删除和修改的话,通常传到后台的肯定含有对象的ID项,那么这个ID是怎么获取的呢,通过acItemsSelected.xxxId能获取,那么这个xxxId必须是在DataGrid中有,设置为不显示就好了,例如我就是这么做的
<mx:DataGridColumn visible="false" dataField="targetCalId" />
这样的话,要更改的数据等都能通过ID传到后台查询相应对象更改删除了,接下来的事是比较重要的,如果光删除数据库是不行的,页面数据也要保持同步,关于dataGrid也没有好的刷新方法,所以你上网一搜,可能有的人会告诉你对于删除这样做:dataArray.removeItemAt(myGrid.selectedIndex);
增加这样做:dataArray.addItemAt(obj,0);
修改这样做:dataArray.setItemAt(obj,myGrid.selectedIndex);
这里说的dataArray是指的是DataGrid的DataProvider的值集合【当然肯定得声明称全局变量】
这样的写法呢可能你觉得,哎,是对的,其实不然,这并没有真正起到作用,对于FLEX来说缓存是相当大的,不行的话你通过这个修改行记录的属性后,再点这行记录的属性编辑页面发现值根本没改,所以所没有进行二次查询数据库了,利用的是缓存。即便是你调用了初始化查询数据库的那个方法,也是不行的,还是有缓存,最好的做法就是,抛弃上面的三种写法,只需要两步就可以实现刷新,第一初始化DataGrid的那个方法请求必须是URLRequest的,添加一个参数类似于
var u:URLVariables=new URLVariables("temp="+Math.random());
当然不一定非要是temp什么名字都行,然后在返回操作成功提示后调用这个初始化方法,你会发现真的起作用了。
其实建议关于URLRequest传参数的最好带上这个参数,也不费事,可以在很多场合下解决缓存不更新问题
说了这么多其实就是先做好个思想准备,理清思路,下面我就贴上我的一段代码
mxml文件
- <span style="font-size: medium;"><?xml version="1.0" encoding="utf-8"?>
- <s:TitleWindow xmlns:fx="http://ns.adobe.com/mxml/2009"
- xmlns:s="library://ns.adobe.com/flex/spark"
- xmlns:mx="library://ns.adobe.com/flex/mx" width="668" height="326"
- creationComplete="initComponent()"
- title="指标计量单位"
- fontSize="15"
- close="closeWindow()">
- <s:layout>
- <s:VerticalLayout />
- </s:layout>
- <fx:Declarations>
- <mx:StringValidator id="sval_1" source="{targetTypeName}" property="text"
- tooShortError="字符串太短了,请输入最少4个字符. "
- tooLongError="字符串太长了,请输入最长20个字符. "
- minLength="4" maxLength="20"
- trigger="{myButton}" triggerEvent="click"
- />
- <mx:StringValidator id="sval_2" source="{targetCal}" property="text"
- tooShortError="字符串太短了,请输入最少4个字符. "
- tooLongError="字符串太长了,请输入最长20个字符. "
- minLength="4" maxLength="20"
- trigger="{myButton}" triggerEvent="click"
- />
- </fx:Declarations>
- <fx:Script>
- <![CDATA[
- import com.adobe.serialization.json.JSON;
- import mx.collections.ArrayCollection;
- import mx.controls.Alert;
- import mx.events.CloseEvent;
- import mx.events.ListEvent;
- import mx.managers.PopUpManager;
- import mx.rpc.events.ResultEvent;
- import mx.utils.URLUtil;
- import mx.validators.Validator;
- import org.osmf.utils.URL;
- [Bindable]public static var mainApp:DataCenterTargetPreserve = null;
- [Bindable]public var gsMyString:String;
- [Bindable]public var gnMyNumber:Number;
- [Bindable]public var acItemsSelected:Object;
- [Bindable]
- public var dataArray:ArrayCollection;
- private function initComponent():void
- {
- var u:URLVariables=new URLVariables("temp="+Math.random());
- var r:URLRequest=new URLRequest();
- r.data=u;
- r.method=URLRequestMethod.POST;
- r.url=mainApp.urls+"/findTargetCal.do";
- var l:URLLoader=new URLLoader();
- l.load(r);
- l.addEventListener(Event.COMPLETE, comp2);
- }
- function comp2(e:Event):void
- {
- var l:URLLoader=URLLoader(e.target);
- var array:Array=JSON.decode(String(l.data)) as Array;
- dataArray=new ArrayCollection(array);
- myGrid.dataProvider=dataArray;
- }
- private function closeWindow():void
- {
- PopUpManager.removePopUp(this);
- }//closeWindow
- private function showFinalSelection(oEvent:Event):void
- {
- //mainApp.tiFinalSelection.text = oEvent.target.selectedItem.album;
- }//showFinalSelection
- protected function button1_clickHandler(event:MouseEvent):void
- {
- PopUpManager.removePopUp(this);
- }
- protected function button2_clickHandler(event:MouseEvent):void
- {
- var all:Array=Validator.validateAll([sval_1,sval_2]);
- if(all.length==0){
- var v:URLVariables=new URLVariables("targetTypeName="+targetTypeName.text+"&targetCal="+targetCal.text+"&temp="+Math.random());
- var r:URLRequest=new URLRequest();
- r.url=mainApp.urls+"/addTargetCal.do";
- r.method=URLRequestMethod.POST;
- r.data=v;
- var l:URLLoader=new URLLoader();
- l.load(r);
- l.addEventListener(Event.COMPLETE,comp);
- }else{
- Alert.show("新增失败");
- }
- }
- private function comp(e:Event):void{
- var l:URLLoader = URLLoader(e.target);
- var o:Object=URLUtil.stringToObject(l.data,";",true);
- if(o.result=="add"){
- Alert.show("新增成功");
- var obj:Object=(JSON.decode(o.datas) as Object);
- //dataArray.addItemAt(obj,0);
- Alert.show(obj.targetCalId);
- }
- initComponent();
- }
- private function myClick(evt:CloseEvent):void{
- //Alert.show("本次要删除的为"+mainDataGrid.selectedIndex);
- if(evt.detail==Alert.YES){
- //Alert.show(acItemsSelected.getItemAt(0).targetId);
- var v:URLVariables = new URLVariables("id="+acItemsSelected.targetCalId+"&temp="+Math.random());
- var r:URLRequest = new URLRequest();
- r.url =mainApp.urls+"/deleteTargetCal.do" ;
- r.method = URLRequestMethod.POST;
- r.data=v;
- var l:URLLoader = new URLLoader();
- l.load(r);
- //dataArray.removeItemAt(myGrid.selectedIndex);
- l.addEventListener(Event.COMPLETE,comp1); //注册请求完成后 响应获取数据事件方法
- }
- }
- private function comp1(e:Event):void
- {
- var l:URLLoader = URLLoader(e.target);
- var o:Object = URLUtil.stringToObject(l.data, ";", true);
- if(o.result=="delete"){
- Alert.show("删除成功!","友情提示");
- }
- initComponent();
- }
- protected function button3_clickHandler(event:MouseEvent):void
- {
- if(myGrid.selectedItem==null){
- Alert.show("请选择一项进行删除","友情提示");
- }else{
- var dlg_obj:Object=Alert.show("确认删除吗?", "友情提示!", Alert.YES|Alert.NO,null,myClick);
- }
- }
- protected function button4_clickHandler(event:MouseEvent):void
- {
- if(myGrid.selectedItem==null){
- Alert.show("请选择一项进行修订!","友情提示");
- }else{
- var v:URLVariables = new URLVariables("targetTypeName="+targetTypeName.text+"&targetCal="+targetCal.text+"&id="+acItemsSelected.targetCalId);
- var r:URLRequest = new URLRequest();
- r.url =mainApp.urls+"/updateTargetCal.do";
- r.method = URLRequestMethod.POST;
- r.data = v;
- var l:URLLoader = new URLLoader();
- l.load(r);
- l.addEventListener(Event.COMPLETE,comp3); //注册请求完成后 响应获取数据事件方法
- }
- }
- private function comp3(e:Event):void
- {
- var l:URLLoader = URLLoader(e.target);
- var o:Object = URLUtil.stringToObject(l.data, ";", true);
- if(o.result=="update"){
- Alert.show("更新成功!","友情提示");
- var obj:Object=(JSON.decode(o.datas) as Object);
- //dataArray.setItemAt(obj,myGrid.selectedIndex);
- }else{
- Alert.show("操作失败!","友情提示");
- }
- initComponent();
- }
- protected function myGrid_itemClickHandler(event:ListEvent):void
- {
- acItemsSelected =myGrid.selectedItem;
- }
- ]]>
- </fx:Script>
- <mx:Form width="651" height="282">
- <mx:DataGrid width="616" height="160" id="myGrid" itemClick="myGrid_itemClickHandler(event)">
- <mx:columns>
- <mx:DataGridColumn headerText="计量名称" dataField="targetTypeName"/>
- <mx:DataGridColumn headerText="计量符号" dataField="targetCal"/>
- <mx:DataGridColumn visible="false" dataField="targetCalId" />
- </mx:columns>
- </mx:DataGrid>
- <mx:HBox>
- <s:Label width="33"/>
- <mx:FormItem label="计量名称" >
- <s:TextInput id="targetTypeName"/>
- </mx:FormItem>
- <mx:FormItem label="计量符号" >
- <s:TextInput id="targetCal"/>
- </mx:FormItem>
- <mx:FormItem >
- <s:Button label="新增" id="myButton" click="button2_clickHandler(event)" />
- </mx:FormItem>
- </mx:HBox>
- <mx:FormItem >
- </mx:FormItem>
- <mx:HBox>
- <s:Label width="250"/>
- <mx:FormItem >
- <s:Button label="删除" click="button3_clickHandler(event)"/>
- </mx:FormItem>
- <mx:FormItem >
- <s:Button label="修改" click="button4_clickHandler(event)"/>
- </mx:FormItem>
- <mx:FormItem >
- <s:Button label="刷新"/>
- </mx:FormItem>
- <mx:FormItem >
- <s:Button label="关闭" click="button1_clickHandler(event)"/>
- </mx:FormItem>
- </mx:HBox>
- </mx:Form>
- </s:TitleWindow>
- </span>
关于上面这个程序的mainApp就不用管它,它只是主应用程序而已,细心的可以发现这个是个弹出窗口程序
关于这个程序的三个Servletet处理类【只贴上关键代码】
FindTargetCalServlet
- <span style="font-size: medium;">public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- request.setCharacterEncoding("UTF-8");
- TTargetCalDAO dao=new TTargetCalDAO();
- List<TTargetCal> cals=dao.findAll();
- JSONArray json = JSONArray.fromObject(cals);
- String datas = json.toString();
- System.out.println(datas);
- System.out.println(datas);
- response.setCharacterEncoding("UTF-8");
- response.getWriter().write(datas);
- }</span>
DeleteTargetCalServlet
- <span style="font-size: medium;">public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- TTargetCalDAO dao = new TTargetCalDAO();
- String id = request.getParameter("id");
- if (DataOptUtils.isNotNull(id)) {
- TTargetCal rr = dao.findById(Integer.valueOf(id));
- dao.delete(rr);
- }
- response.setCharacterEncoding("UTF-8");
- response.getWriter().write("result=delete");
- }</span>
AddTargetCalServlet
- <span style="font-size: medium;">public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- request.setCharacterEncoding("UTF-8");
- TTargetCalDAO dao=new TTargetCalDAO();
- String targetCal=request.getParameter("targetCal");
- String targetTypeName=request.getParameter("targetTypeName");
- TTargetCal cal=new TTargetCal();
- cal.setTargetCal(targetCal);
- cal.setTargetTypeName(targetTypeName);
- dao.save(cal);
- TTargetCal re =dao.findById(dao.findLastId());
- JSONObject json = JSONObject.fromObject(re);
- String datas = json.toString();
- response.getWriter().write("result=add;datas=" + datas);
- }</span>
UpdateTargetCalServlet
- <span style="font-size: medium;">public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- request.setCharacterEncoding("UTF-8");
- response.setCharacterEncoding("UTF-8");
- TTargetCalDAO dao = new TTargetCalDAO();
- String targetTypeName = request.getParameter("targetTypeName");
- String targetCal = request.getParameter("targetCal");
- String id = request.getParameter("id");
- if (DataOptUtils.isNotNull(id)) {
- TTargetCal rr = dao.findById(Integer.valueOf(id));
- if(DataOptUtils.isNotNull(targetCal)){
- rr.setTargetCal(targetCal);
- }
- if(DataOptUtils.isNotNull(targetTypeName)){
- rr.setTargetTypeName(targetTypeName);
- }
- dao.merge(rr);
- TTargetCal tc = dao.findById(rr.getTargetCalId());
- JSONObject json = JSONObject.fromObject(tc);
- String datas = json.toString();
- response.getWriter().write("result=update;datas=" + datas);
- }
- }</span>
这里的DataOptUtils是我写的一个数据处理类,判断是否为空什么的
还有就是TTargetCal
- <span style="font-size: medium;">@Entity
- @Table(name = "t_target_cal", catalog = "sxtele")
- public class TTargetCal implements java.io.Serializable {
- // Fields
- private Integer targetCalId;
- private String targetCal;
- private String targetTypeName;
- // Constructors
- /** default constructor */
- public TTargetCal() {
- }
- /** minimal constructor */
- public TTargetCal(String targetCal) {
- this.targetCal = targetCal;
- }
- /** full constructor */
- public TTargetCal(String targetCal, String targetTypeName) {
- this.targetCal = targetCal;
- this.targetTypeName = targetTypeName;
- }
- // Property accessors
- @Id
- @GeneratedValue
- @Column(name = "Target_cal_id", unique = true, nullable = false)
- public Integer getTargetCalId() {
- return this.targetCalId;
- }
- public void setTargetCalId(Integer targetCalId) {
- this.targetCalId = targetCalId;
- }
- @Column(name = "Target_cal", nullable = false, length = 50)
- public String getTargetCal() {
- return this.targetCal;
- }
- public void setTargetCal(String targetCal) {
- this.targetCal = targetCal;
- }
- @Column(name = "Target_type_name", length = 50)
- public String getTargetTypeName() {
- return this.targetTypeName;
- }
- public void setTargetTypeName(String targetTypeName) {
- this.targetTypeName = targetTypeName;
- }
- }</span>