GXT开发:动态字段Grid的生成

这几天,因项目的需要。要在GXT中实现一个Grid,带PagingToolbar和CheckBoxColumn 。最重要的是这个Grid,访问的数据表,是其他用户定义的,在访问的时候不知道表的数据结构。所以,前端展示面临动态生成ColumnModel 的问题。查询GXT的事例发现所有的例子都是如下定义ColumnConfig:

ColumnConfig<Post, String> forumColumn = new ColumnConfig<Post, String>(properties.forum(), 150, "Forum");
ColumnConfig<Post, String> usernameColumn = new ColumnConfig<Post, String>(properties.username(), 150, "Username");
ColumnConfig<Post, String> subjectColumn = new ColumnConfig<Post, String>(properties.subject(), 150, "Subject");
ColumnConfig<Post, Date> dateColumn = new ColumnConfig<Post, Date>(properties.date(), 150, "Date");

这里的Post 是一个已知的数据结构。这里不可能先给出一个确定的数据结构。怎么办?

我这里用了一个ColumnValueProvider 和 Row对象来实现这个动态的数据结构。

public static class Row
    {
        private static int nextId;

        private final Map<String,String> columnsMap;
        private final String key = "Row" + Integer.toString(nextId++);

        public Row() {
              columnsMap = new HashMap<String, String>();
        }

        public String getColumn(String columnName) {
          return columnsMap.get(columnName);
        }

        public String getKey() {
          return key;
        }

        public void setValue(String columnName, String value) {
          columnsMap.put(columnName, value);
        }

      }

      /**
       * A model key provider that supports a spreadsheet-like table with an arbitrary number of rows.
       */
      public class RowKeyProvider implements ModelKeyProvider<Row>
      {
        @Override
        public String getKey(Row row) {
          return row.getKey();
        }
      }

      /**
       * A value provider that supports a spreadsheet-like table with an arbitrary number of rows.
       */
      public class RowValueProvider
      {
        public ValueProvider<Row, String> getColumnValueProvider(int columnIndex,String columnName) {
          return new ColumnValueProvider(columnIndex,columnName);
        }
      }

      public static class ColumnValueProvider implements ValueProvider<Row, String>
      {
            private static int nextId;

//            private final int columnIndex;
            private final String columnName;
            private final String path = "Column" + Integer.toString(nextId++);

            public ColumnValueProvider(int columnIndex, String columnName) {
//              this.columnIndex = columnIndex;
              this.columnName = columnName;
            }

            @Override
            public String getPath() {
              return path;
            }

            @Override
            public String getValue(Row row) {
              return row.getColumn(columnName);
            }

            @Override
            public void setValue(Row row, String value) {
              row.setValue(columnName, value);
            }  

      }

定义的Grid,且该Grid是一个空Grid:

public void setGridPanel(XmlUtils xmlUtils)
    {        

        final ToolBar headerToolbar = new ToolBar();
        headerToolbar.setSpacing(2);    

        headerToolbar.add(deleteBtn);
        headerToolbar.add(addBtn);        

        pagingToolBar = new PagingToolBar(30);
        pagingToolBar.getElement().getStyle().setProperty("borderBottom", "none");
        pagingToolBar.setSpacing(2);

        String path = "HttpService";
        RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, path);

        RequestFactoryProxy <TablePagingLoadConfig, PagingLoadResult<Row>> proxy = new RequestFactoryProxy<TablePagingLoadConfig, PagingLoadResult<Row>>() {
            @Override
            public void load(final TablePagingLoadConfig loadConfig, final Receiver<? super PagingLoadResult<Row>> receiver) {
                RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, "HttpService");
                HttpProxy<TablePagingLoadConfig> httpProxy = new HttpProxy<TablePagingLoadConfig>(builder);
                httpProxy.load(loadConfig, new Callback<String, Throwable>() {
                    @Override
                    public void onSuccess(String result) {
                        XmlUtils xml = new XmlUtils(XMLParser.parse(result));
                        String statusCode = xml.getStatus().getCode();
                        if(! statusCode.equals("0000"))
                        {
                            String msg = xml.getStatus().getMessage();
                            String exp = xml.getStatus().getException();
                            Client.INSTANCE.showErrWin("Error", msg, exp);
                            return;
                        }
                        Element root = xml.getRootElement();
                        NodeList recordsList = root.getElementsByTagName("records");
                        Element recordsElement = (Element) recordsList.item(0);
                        int allCount = Integer.parseInt(recordsElement.getAttribute("allCount"));
                        int currentCount = Integer.parseInt(recordsElement.getAttribute("currentCount"));

                        NodeList nodeList = root.getElementsByTagName("record");
                        List<Row> records = new ArrayList<Row>();
                        for(int i = 0 ; i < nodeList.getLength() ; i ++)
                        {
                            Row row = new Row();
                            Element record = (Element) nodeList.item(i);
                            for(int j = 0 ; j < record.getChildNodes().getLength(); j++)
                            {
                                Element column = (Element) record.getChildNodes().item(j);
                                String columnName = column.getAttribute("name");
                                String columnValue = column.getAttribute("value");
                                row.setValue(columnName, columnValue);
                            }
                            records.add(row);
                        }

                        receiver.onSuccess(new PagingLoadResultBean<Row>(records, allCount, loadConfig.getOffset()));
                    }

                    @Override
                    public void onFailure(Throwable reason) {

                    }
               });
            }
        };

//        HttpProxy<TablePagingLoadConfig> httpProxy = new HttpProxy<TablePagingLoadConfig>(builder);

        XmlReader<TablePagingLoadResult<Row>, DataCollection> reader = new XmlReader<TablePagingLoadResult<Row>, DataCollection>(
                XmlAutoBeanFactory.instance, DataCollection.class) {
//            protected PagingLoadResult<Map<String,String>> createReturnData(Object loadConfig, DataCollection records) {
//                return new PagingLoadResultBean<Map<String,String>>(records.getValues());
//            }
        };
        IdentityValueProvider<Row> identity = new IdentityValueProvider<Row>();

        selectionModel = new CheckBoxSelectionModel<Row>(identity);
        loader = new PagingLoader<TablePagingLoadConfig, TablePagingLoadResult<Row>>((DataProxy)proxy);

        loader.useLoadConfig(new TablePagingLoadConfig(this));

        store = new ListStore<Row>(new RowKeyProvider());
        store.setAutoCommit(true);

        loader.addLoadHandler(new LoadResultListStoreBinding<TablePagingLoadConfig, Row, TablePagingLoadResult<Row>>(store));

        List<ColumnConfig<Row, ?>> l = new ArrayList<ColumnConfig<Row, ?>>();

        cm = null;
        grid = null;

        ValueProvider<Row, String> cvp = rvp.getColumnValueProvider(0,"");
        ColumnConfig<Row, String> column = new ColumnConfig<Row, String>(cvp, 100, "NoTitle");
        l.add(column);
        cm = new ColumnModel<Row>(l);

        grid = new Grid<Row>(store, cm);
        grid.setSelectionModel(selectionModel);
//        grid.getView().setForceFit(true);
        grid.setBorders(false);
        grid.setLoader(loader);

        pagingToolBar.bind(loader);

        FramedPanel cp = new FramedPanel();
        HorizontalLayoutContainer toolbarPanel = new HorizontalLayoutContainer();
        toolbarPanel.setStyleName("toolbarPanel");
        toolbarPanel.setHeight(30);
        toolbarPanel.setWidth(-1);
        toolbarPanel.add(headerToolbar,new HorizontalLayoutData(1, 30, new Margins(0)));
        toolbarPanel.add(pagingToolBar,new HorizontalLayoutData(-1, 30, new Margins(0)));
        cp.setHeaderVisible(false);
        cp.setBorders(false);
        cp.setWidth("100%");
        cp.setStyleName("gridHeaderPanel");
        cp.add(toolbarPanel);
        VerticalLayoutContainer verticalLayoutContainer = new VerticalLayoutContainer();
        verticalLayoutContainer.setBorders(false);
        verticalLayoutContainer.add(cp, new VerticalLayoutData(1, 30, new Margins(-8,0,0,0)));
        verticalLayoutContainer.add(grid, new VerticalLayoutData(1, 1));

        gridPanel.add(verticalLayoutContainer);
    }

生成Grid 的数据结构:

private void refreshGrid(XmlUtils xmlUtils)
    {
        //TODO: refresh the grid
        tableStructure = xmlUtils;
        List<ColumnConfig<Row, ?>> l = new ArrayList<ColumnConfig<Row, ?>>();

        if(xmlUtils != null)
        {
//            loader.addLoadHandler(new LoadResultListStoreBinding<PagingLoadConfig, Map<String,String>, PagingLoadResult<Map<String,String>>>(store));

            Element respEle = xmlUtils.getResponseElement();
            NodeList nodeList = respEle.getElementsByTagName("COLUMN");

            l.add(selectionModel.getColumn());

            for(int i = 0 ; i < nodeList.getLength(); i++)
            {
                  Element currentElement = (Element) nodeList.item(i);

                  String COLUMN_NAME = currentElement.getAttribute("COLUMN_NAME");
                  String DATA_TYPE = currentElement.getAttribute("DATA_TYPE");
                   String IS_NULLABLE = currentElement.getAttribute("IS_NULLABLE");
                   String COLUMN_KEY = currentElement.getAttribute("COLUMN_KEY");
                   String CHARACTER_MAXIMUM_LENGTH = currentElement.getAttribute("CHARACTER_MAXIMUM_LENGTH");
                int columnWidth = Integer.parseInt(CHARACTER_MAXIMUM_LENGTH);
                   ValueProvider<Row, String> cvp = rvp.getColumnValueProvider(i,COLUMN_NAME);

                   ColumnConfig<Row, String> column = new ColumnConfig<Row, String>(cvp, 100, COLUMN_NAME);

                   l.add(column);
            }
        }

        cm = new ColumnModel<Row>(l);

        if(this.getCurrentTableData().isPersonal())
        {
            if(rowEditing!=null)
            {
                rowEditing.setEditableGrid(null);
                rowEditing = null;
            }
            rowEditing = createGridEditing(grid);

        }
        else
        {
            if(rowEditing!=null)
            {
                rowEditing.setEditableGrid(null);
                rowEditing = null;
            }
        }

//        rowEditing.addEditor((ColumnConfig<Row,Boolean>)l.get(0), new Label(""));
        if(xmlUtils != null)
        {
              Element respEle = xmlUtils.getResponseElement();
            NodeList nodeList = respEle.getElementsByTagName("COLUMN");    

//            rowEditing.addEditor((selectionModel.getColumn()) l.get(0), new CheckBox());

            for(int i = 0; i < nodeList.getLength();i++)
            {

                Element currentElement = (Element) nodeList.item(i);
                String COLUMN_KEY = "";
                final int CHARACTER_MAXIMUM_LENGTH = Integer.parseInt(currentElement.getAttribute("CHARACTER_MAXIMUM_LENGTH"));
                if(currentElement!=null)
                {
                    COLUMN_KEY = currentElement.getAttribute("COLUMN_KEY");
                }

                if(this.getCurrentTableData().isPersonal())
                {
                    final TextField tf = new TextField();
                    tf.addKeyDownHandler(new KeyDownHandler(){

                        @Override
                        public void onKeyDown(KeyDownEvent event) {
                            if(tf.getText().length()>= CHARACTER_MAXIMUM_LENGTH)
                            {
                                tf.setText(tf.getText().substring(0,CHARACTER_MAXIMUM_LENGTH - 1));
                            }
                        }

                    });
//                    tf.addKeyDownHandler(new KeyDownHandler(){
//                        @Override
//                        public void KeyDown(Event event) {
//                            //TODO:Query Submit
//
//                        }
//                    });
                       rowEditing.addEditor((ColumnConfig<Row,String>)l.get(i + 1),tf);
                }
            }

            grid.setLoader(loader);
        }

        grid.reconfigure(store, cm);
        grid.getStore().clear();
    }
时间: 2024-10-10 02:03:39

GXT开发:动态字段Grid的生成的相关文章

如何根据动态SQL代码自动生成DTO

当前的状况 一般做数据库相关开发, 除非学习, 否则很少有人愿意直接使用JDBC.本来Java代码就比较啰嗦了,而直接用JDBC写代码之啰嗦简直有些令人发狂!所以在实际开发过程中,我们通常都会使用一些框架/库来帮助我们操作数据库.而且开源市场上的选择也比较多,就我个人接触到的有:Hibernate,MyBatis,JdbcTemplate,DbUtils,ActiveRecord,JavaLite等等. 这些框架都能大幅的提高开发效率,对于一些基本CRUD操作来说,虽然各有差异,但总的来说基本是

在javaEE下学习web(在eclipse中开发动态的WEB工程,servlet的环境搭建,及servlet的一些方法)

一个简便的方法实现javaee版的eclipse开发动态的WEB工程(javaWEB项目)1.把开发选项切换到javaEE2. 可以在window->shou view 中找到package explorer并把其拖到开发区的左边 (Tomcat环境搭建在这不多说)3.在servers面板中新建Tomcat服务器,一定要关联到Tomcat安装的根目录4.新建一个Dynamic Web Project.其中Target Runtime需选择Tomcat6.0(3)5.开发java WEB应用6.可

动态字段

转载 http://www.cnblogs.com/skyblog/p/4122571.html 大部分应用都不需要自动创建表单创建字段的功能,但使用少部分的动态字段还是可以减少不少麻烦.比如电子商务里面的商品,有很多种商品,每种商品按说都需要定义一张表,但那行不通,因为太多了不说,商品种类还是动态增加的,总不能增加一个商品就增加一张表.类似的情况很多,特别是对于现实中有派生关系的对象组,比如奖励,奖励又分很多种,我们也不需要为每一种奖励定义一张表. 使用动态字段可以解决这种情况,一般来说有两种

如何使用Eclipse的NDK开发动态库,静态库

============问题描述============ 如何使用Eclipse的NDK开发动态库,静态库? Eclipse中已经安装了NDK,CDT和Esequoyah并配置(是在网上查的). 我是做C++的,公司业务需要自学Android,对Java也是知道一点皮毛. 在网上查了一些资料,我都没有成功做出最简单的动态库或静态库,郁闷啊! 有没有详细指导? ============解决方案1============ 你去搜一下Android的jni开发,就知道了,一点都不难,不过一般开发ndk

用动态网页技术PHP生成验证码图片的源代码

文件a.php <? //checkNum.php session_start(); function random($len) { $srcstr="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; mt_srand(); $strs=""; for($i=0;$i<$len;$i++){ $strs.=$srcstr[mt_rand(0,35)]; } return strtoupper($strs); } $str=ra

深入探索spring技术内幕(六): JDK动态代理和cglib生成代理

[ JDK生成代理 ] JDK中给我们提供了一个Proxy类可以动态的给我们生成代理. 假定我们要做一个权限管理系统, 需要控制用户对某一个方法的访问. 如果user为null, 那么不让用户访问save方法. ① 接口类: PersonService public interface PersonService { public void save(); } ② 实现类: PersonServiceImpl public class PersonServiceImpl implements P

EXT Js 关于动态收缩grid的宽度

Ext js关于动态收缩grid的宽度导致grid不能正常收缩的解决方案: 1.根据"window.document.body.onresize = function ()"事件动态给grid赋值宽度,达到动态收缩的目的,效果比较好,但是会受到浏览器兼容性的限制 2.根据"Ext.EventManager.onWindowResize(function () "这个Ext自带的方法进行处理,默认会有100毫秒的收缩延迟,效果上不太理想:可以参考源码,进行修改去掉延迟

1.4.5 动态字段

动态字段允许solr索引没有在schema.xml中明确定义的字段,通过提供一个灵活的添加文档的机制,可以使你的应用不会那么脆弱. <dynamicField name="*_i" type="int" indexed="true" stored="true"/> 相关主题 SchemaXML-Dynamic Field

UGUI动态改变Grid大小

工作中经常需要用到Grid,动态添加物体时,就需要动态改变Grid大小.直接写好脚本,以后COPY. using UnityEngine;using System.Collections;using UnityEngine.UI;using System; public class Colve_UpdateGridShow : MonoBehaviour { public GridLayoutGroup m_Grid; private Vector2 cellVec2; private Vect