码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-04-10 19:38:24      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:

这几天,因项目的需要。要在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();
    }

 

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

标签:

原文地址:http://www.cnblogs.com/neyan/p/4415324.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!