Showing posts with label Grid. Show all posts
Showing posts with label Grid. Show all posts

Working with GXT Grid : Add Remote Pagination Functionality

As promised previously today I am going write about adding remote pagination functionality with GXT Grid which was one of most demanded one from my readers. In my previous blog I have described in detail how you can load data from a remote data store and show them in GXT Grid. In this writing the same Comments entity and CommentModel are used to represent data. You will find the code of these classes here.

At first in the implementation of your GWT RPC Service add a method to load all the comments from the data store.

public List<Commentmodel> getAllComment() 
{
   List<Commentmodel> commentList = new ArrayList<Commentmodel>();
   PersistenceManager pm = PMF.get().getPersistenceManager(); 
   try {
      String query = "select from " + Comments.class.getName()+" order by  postedDate desc"; 
      List<Comments> list = (List<Comments>) pm.newQuery(query).execute();
      if (!list.isEmpty()) {
         for (Comments c : list)
         {
            //convert from entity object to DTO
            commentList.add(CommentConverter.entityToModel(c));
         }
      }
   }catch (Exception ex) {}
   finally {
      pm.close();
   }
   return commentList;
}

Now add a method public PagingLoadResult<Commentmodel> getComments(PagingLoadConfig config) in your service which takes a PagingLoadConfig object to determine the limit and offset value of the request and returns the desired list for the paging loader. Here is the implementation of the method.
@Override
public PagingLoadResult<Commentmodel> getComments(PagingLoadConfig config) {

//comments is a private variable of the service implementation class
//private List<Commentmodel> comments;
comments = getAllComment();

//get all the comments from the data store
//and sort this list according to sorting info

if (config.getSortInfo().getSortField() != null) {
final String sortField = config.getSortInfo().getSortField();
if (sortField != null) {
Collections.sort(comments, config.getSortInfo().getSortDir().comparator(new Comparator<Commentmodel>() {
public int compare(CommentModel c1, CommentModel c2) {
if (sortField.equals("comments")) {
return c1.getComments().compareTo(c2.getComments());
} else if (sortField.equals("postedBy")) {
return c1.getPostedBy().compareTo(c2.getPostedBy());
} else if (sortField.equals("postedDate")) {
return c1.getStartingDate().compareTo(c2.getStartingDate());
}
return 0;
}
}));
}
}

//Create a sublist and add data to list according
//to the limit and offset value of the config

ArrayList<Commentmodel> sublist = new ArrayList<Commentmodel>();
int start = config.getOffset();
int limit = comments.size();
if (config.getLimit() > 0) {
limit = Math.min(start + config.getLimit(), limit);
}
for (int i = config.getOffset(); i < limit; i++) {         sublist.add(comments.get(i));       }       
return new BasePagingLoadResult<Commentmodel>
(sublist, config.getOffset(), comments.size());
}

Your server side coding is done. Let's come to client side coding and see how to use this service to add remote pagination functionality with GXT Grid.

First create a RpcProxy object, proxy to make RPC call using the load configuration. With the proxy object create a PagingLoader, loader which is required to load page enabled set of data and enable the remote sorting attribute of the loader.

RpcProxy<PagingLoadResult<CommentModel>> proxy = new RpcProxy<PagingLoadResult<CommentModel>>() {
@Override
public void load(Object loadConfig,
AsyncCallback<PagingLoadResult<CommentModel>> callback) {
Gxtexamplegalary.greetingService.getComments(
(PagingLoadConfig) loadConfig, callback);
}
};

// loader
final PagingLoader<PagingLoadResult<ModelData>> loader = new BasePagingLoader<PagingLoadResult<ModelData>>(
proxy);
loader.setRemoteSort(true);

Now use this loader to create a ListStore of CommentModel  and bind the loader with a PagingToolBar.

ListStore<CommentModel> commentList = new ListStore<CommentModel>(loader);

final PagingToolBar toolBar = new PagingToolBar(3);
toolBar.bind(loader);

Create a List of ColumnConfig  and a ColumnModel from the ColumnConfig list.

List<ColumnConfig> configs = new ArrayList<ColumnConfig>();
ColumnConfig column = new ColumnConfig();
column.setId("comments");
column.setHeader("Comments");
column.setWidth(200);
configs.add(column);

column = new ColumnConfig("postedBy", "Posted By", 150);
column.setAlignment(HorizontalAlignment.LEFT);
configs.add(column);

column = new ColumnConfig("postedDate", "Posting Date", 100);
column.setAlignment(HorizontalAlignment.RIGHT);
column.setDateTimeFormat(DateTimeFormat.getShortDateFormat());
configs.add(column);

ColumnModel cm = new ColumnModel(configs);

Finally create a Grid with the commentList and the column model. Add a Listener with the Grid to handle the remote pagination functionality. In the handleEvent method of the Listener first create a PagingLoadConfig, config and set offset, limit, sort field and sort direction value of the config. Then load data by the loader with this configuration.
final Grid<CommentModel> grid = new Grid<CommentModel>(commentList, cm);
grid.setStateId("pagingGridExample");
grid.setStateful(true);
grid.addListener(Events.Attach, new Listener<GridEvent<CommentModel>>() {
public void handleEvent(GridEvent<CommentModel> be) {
PagingLoadConfig config = new BasePagingLoadConfig();
config.setOffset(0);
config.setLimit(3);

Map<String, Object> state = grid.getState();
if (state.containsKey("offset")) {
int offset = (Integer) state.get("offset");
int limit = (Integer) state.get("limit");
config.setOffset(offset);
config.setLimit(limit);
}
if (state.containsKey("sortField")) {
config.setSortField((String) state.get("sortField"));
config.setSortDir(SortDir.valueOf((String) state
.get("sortDir")));
}
loader.load(config);
}
});
grid.setLoadMask(true);
grid.setBorders(true);
grid.setAutoExpandColumn("comments");
grid.setStyleAttribute("borderTop", "none");
grid.setStripeRows(true);

ContentPanel cp = new ContentPanel();
cp.setBodyBorder(false);
cp.setHeading("Grid with Pagination");
cp.setButtonAlign(HorizontalAlignment.CENTER);
cp.setLayout(new FitLayout());
cp.setSize(700, 300);
cp.add(grid);
cp.setBottomComponent(toolBar);
RootPanel.get().add(cp);

That's all for today. Enjoy GWT and GXT :-)

Google App Engine, JDO and GXT(Ext GWT) Grid - Make All These Working Together

Previously I have written some blogs about GXT Grid  where the data resides in the client side. But as per the request of my readers I feel the necessity of writing some tutorials with remote data store. And for this purpose I have chosen Google App Engine data store as the back-end with JDO implementation.

It requires a configuration file in the final WAR named  jdoconfig.xml which resides in the directory war/WEB-INF/classes/META-INF/. Eclipse creates this file as src/META-INF/jdoconfig.xml. This file is automatically copied into war/WEB-INF/classes/META-INF/ when you build your project. This file should contain the following contains.

<?xml version="1.0" encoding="utf-8"?>
<jdoconfig xmlns="http://java.sun.com/xml/ns/jdo/jdoconfig"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:noNamespaceSchemaLocation="http://java.sun.com/xml/ns/jdo/jdoconfig">

   <persistence-manager-factory name="transactions-optional">
       <property name="javax.jdo.PersistenceManagerFactoryClass"
           value="org.datanucleus.store.appengine.jdo.DatastoreJDOPersistenceManagerFactory"/>
       <property name="javax.jdo.option.ConnectionURL" value="appengine"/>
       <property name="javax.jdo.option.NontransactionalRead" value="true"/>
       <property name="javax.jdo.option.NontransactionalWrite" value="true"/>
       <property name="javax.jdo.option.RetainValues" value="true"/>
       <property name="datanucleus.appengine.autoCreateDatastoreTxns" value="true"/>
   </persistence-manager-factory>
</jdoconfig>

Here I am going to describe the way of loading a comment list from the App Engine data store and making the list viewable in the GXT Grid. So At first I need a POJO class to store and retrieve comments from the App Engine data store using the JDO API. Here is my Comments class.

@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class Comments {
    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Long id;

    @Persistent
    @Column(name="comments")
    private String comments;

    @Persistent
    @Column(name="posted_by")
    private String postedBy;
    
    @Persistent
    @Column(name="posted_date")
    private Date postedDate;

    public Comments(String comments, String postedBy, Date date) {
        this.comments = comments;
        this.postedDate = date;
        this.postedBy = postedBy;
   }

    public Long getId() {
        return id;
    }

 public String getComments() {
  return comments;
 }

 public void setComments(String comments) {
  this.comments = comments;
 }

 public Date getPostedDate() {
  return postedDate;
 }

 public void setPostedDate(Date postedDate) {
  this.postedDate = postedDate;
 }

 public void setId(Long id) {
  this.id = id;
 }

 public String getPostedBy() {
  return postedBy;
 }

 public void setPostedBy(String postedBy) {
  this.postedBy = postedBy;
 }
}

Now when you want to transfer data from server to client you need a DTO (Data Transfer Object). As I am going to show the comments in GXT Grid so my DTO has to inherit the properties of GXT's BaseModel. Here is the CommentModel class which will serve my purposes.

public class CommentModel extends BaseModel {

private static final long serialVersionUID = 1L;

public CommentModel(){}

public CommentModel(String comments, String postedBy, Date date) {
set("comments", comments);
set("postedDate", date);
set("postedBy",postedBy);
}

public String getComments() {
return (String) get("comments");
}

public String getPostedBy() {
return (String) get("postedBy");
}

public Date getStartingDate() {
return ((Date) get("postedDate"));
}
}

For any operation on data store you have to request the data store for the desired operation. Each request that uses the data store creates a new instance of the PersistenceManager class through the instance of  PersistenceManagerFactory class. As creating an instance of PersistenceManagerFactory class is a very costly process, I have used a Singleton class PMF for this purpose.

public final class PMF {
private static final PersistenceManagerFactory pmfInstance =
JDOHelper.getPersistenceManagerFactory("transactions-optional");

private PMF() {}

public static PersistenceManagerFactory get() {
return pmfInstance;
}
}

If you are familiar with GWT RPC Service then create a service named CommentService and add a method
List<CommentModel> getAllComment();. Here is the implementation of the method where JDOQL is used to write a query which returns all the comments from the data store.

public List<Commentmodel> getAllComment() 
{
   List<Commentmodel> commentList = new ArrayList<Commentmodel>();
   PersistenceManager pm = PMF.get().getPersistenceManager(); 
   try {
      String query = "select from " + Comments.class.getName()+" order by  postedDate desc"; 
      List<Comments> list = (List<Comments>) pm.newQuery(query).execute();
      if (!list.isEmpty()) {
         for (Comments c : list)
         {
            //convert from entity object to DTO
            commentList.add(CommentConverter.entityToModel(c));
         }
      }
   }catch (Exception ex) {}
   finally {
      pm.close();
   }
   return commentList;
}

CommentConverter is a utility class which converts an object of Comments class to an object of CommentModel class.

public class CommentConverter 
{
   public static CommentModel entityToModel(Comments comment)
   {
      CommentModel model = new CommentModel(comment.getComments(), comment.getPostedBy(), comment.getPostedDate());
      return model;
   }
} 

All the server side coding is done. Let's come to client side.

First create an instance of CommentServiceAsync.
public static final CommentServiceAsync commentService = GWT.create(CommentService.class);
 

Then create a ListStore of CommentModel, commentStore and call the getAllComment method of the commentService. In the onSuccess method add the returned list to the commentStore.
 final Label lbError = new Label();
  final ListStore<Commentmodel> commentStore = new ListStore<Commentmodel>();
  commentService.getAllComment(new AsyncCallback<List<Commentmodel>>() {

   @Override
   public void onFailure(Throwable caught) {
    lbError.setText("data loading failure");

   }

   @Override
   public void onSuccess(List<Commentmodel> result) {
    commentStore.add(result);

   }
  }); 

The rest of the tasks are very familiar with the GXT users. Creating a List of ColumnConfig, a Grid with the commentStore and  ColumnConfig lists, etc.

        List<Columnconfig> configs = new ArrayList<Columnconfig>();
        ColumnConfig column = new ColumnConfig();
        column.setId("comments");
        column.setHeader("Comments");
        column.setWidth(200);
        configs.add(column);

        column = new ColumnConfig("postedBy", "Posted By", 150);
        column.setAlignment(HorizontalAlignment.LEFT);
        configs.add(column);

        column = new ColumnConfig("postedDate", "Posting Date", 100);
        column.setAlignment(HorizontalAlignment.RIGHT);
        column.setDateTimeFormat(DateTimeFormat.getShortDateFormat());
        configs.add(column);

        ColumnModel cm = new ColumnModel(configs);

        final Grid<Commentmodel> grid = new Grid<Commentmodel>(commentStore, cm);
        grid.setBorders(true);
        grid.setAutoExpandColumn("comments");
        grid.setStyleAttribute("borderTop", "none");
        grid.setStripeRows(true);

        ContentPanel cp = new ContentPanel();
        cp.setBodyBorder(false);
        cp.setHeading("Grid with Pagination");
        cp.setButtonAlign(HorizontalAlignment.CENTER);
        cp.setLayout(new FitLayout());
        cp.setSize(700, 300);
        cp.add(grid);

That's all for today. You will get a live example of this tutorial here.
For more about Google App Engine and JDO visit this.

Working with GXT(Ext GWT) Grid : Create an Editable Grid

Last week i was so busy that i can not afford to manage time on writing. And i am afraid that whether i can keep my promise on writing a series of tutorials about GXT and GWT or not. In the upcoming days i have to work in six! projects simultaneously. Good thing is that there will be a lot of new things that i can learn and surely i will share those here whenever i get time. Now i will show you how you can make a GXT Grid editable with TextField, ComboBox and Date Picker.

Create a new project named GxtEditableGrid and add GXT library in the project. As like my previous blogs about GXT Grid i have used the same Employee model and TestData class for generating data. You will find the code of these classes here. Go to the onModuleLoad method of GxtEditableGrid class and remove all the auto generated code of this method.

Starting with creating a list of ColumnConfig and a ColumnConfig instance named column. Configure this column to show and edit Employee Name first. To add the editing functionality create a TextField and a CellEditor with this TextField. Then set the CellEditor as the editor of the column.

List<ColumnConfig> configs = new ArrayList<ColumnConfig>();
ColumnConfig column = new ColumnConfig();
column.setId("name");
column.setHeader("Employee Name");
column.setWidth(200);
TextField<String> text = new TextField<String>();  
text.setAllowBlank(false);  
text.setAutoValidate(true);  
column.setEditor(new CellEditor(text));
configs.add(column); 



For the Department column rather than using a TextField we are going to use a ComboBox to edit this field. First create a SimpleComboBox and add the possible values to it.

final SimpleComboBox<String> combo = new SimpleComboBox<String>();  
combo.setTriggerAction(TriggerAction.ALL);  
combo.add("General Administration");  
combo.add("Information Technology");  
combo.add("Marketing");  
combo.add("Accounts"); 

Then create a CellEditor with the SimpleComboBox and set it as the editor of the department column.

CellEditor editor = new CellEditor(combo) {  
@Override  
public Object preProcessValue(Object value) {  
if (value == null) {  
return value;  
}  
return combo.findModel(value.toString());  
}  

@Override  
public Object postProcessValue(Object value) {  
if (value == null) {  
return value;  
}  
return ((ModelData) value).get("value");  
}  
};  

column = new ColumnConfig("department", "Department", 150);
column.setAlignment(HorizontalAlignment.LEFT);
column.setEditor(editor);  
configs.add(column);

For the Designation column configure it like the Employee Name column and for the Salary column set a cell editor with NumberField. That is this field will only accept numeric values.

column = new ColumnConfig("designation", "Designation", 150);
column.setAlignment(HorizontalAlignment.LEFT);
TextField<String> text2 = new TextField<String>();  
text2.setAllowBlank(false);  
text2.setAutoValidate(true);  
column.setEditor(new CellEditor(text2));
configs.add(column);

column = new ColumnConfig("salary", "Slary", 100);  
column.setAlignment(HorizontalAlignment.RIGHT);  
final NumberFormat number = NumberFormat.getFormat("0.00");  
GridCellRenderer<Employee> checkSalary = new GridCellRenderer<Employee>() {  
public String render(Employee model, String property, ColumnData config, int rowIndex,  
int colIndex, ListStore<Employee> employeeList, Grid<Employee> grid) {  
double val = (Double) model.get(property);  
String style = val < 70000 ? "red" : "green";  
return "<span style='color:" + style + "'>" + number.format(val) + "</span>";
}  
};  
column.setRenderer(checkSalary); 
column.setEditor(new CellEditor(new NumberField()));  
configs.add(column);

To change date field in a Grid with date picker create a DateField, set a date fomat for the DateField and finally set this as the editor for the ColumnConfig.

DateField dateField = new DateField();  
dateField.getPropertyEditor().setFormat(DateTimeFormat.getFormat("MM/dd/y"));

column = new ColumnConfig("joiningdate", "Joining Date", 100);
column.setAlignment(HorizontalAlignment.RIGHT);
column.setEditor(new CellEditor(dateField));  
column.setDateTimeFormat(DateTimeFormat.getMediumDateFormat());
configs.add(column);

To enable the editable functionality of grid you have to create an instance of EditorGrid class instead of a Grid class now. Other things are described in my previous tutorials about GXT Grid.

ListStore<Employee> employeeList = new ListStore<Employee>();
employeeList.add(TestData.getEmployees());
ColumnModel cm = new ColumnModel(configs);

final EditorGrid<Employee> grid = new EditorGrid<Employee>(employeeList, cm);
grid.setStyleAttribute("borderTop", "none");
grid.setAutoExpandColumn("name");
grid.setBorders(true);
grid.setStripeRows(true);

ContentPanel cp = new ContentPanel();
cp.setBodyBorder(false);
cp.setHeading("Employee List");
cp.setButtonAlign(HorizontalAlignment.CENTER);
cp.setLayout(new FitLayout());
cp.setSize(700, 300);
cp.add(grid);
RootPanel.get().add(cp);

That's all. Run the application check the magic GXT. To view the live demo of this tutorial Click here.

editableGrid

Working with GXT(Ext GWT) Grid : Add Grouping Funtionality

Grouping is very helpful when you view a large set of data. It creates a more readable view for the user. GXT provides us with a very easy way of adding grouping functionality with a grid. Here i describe how to add grouping functionality with GXT grid.

Create a new project named GxtGridGrouping and add GXT library in the project. As like my previous blogs about GXT Grid i have used the same Employee model and TestData class for generating data. You will find the code of these classes here. Go to the onModuleLoad method of GxtGridGrouping class and remove all the auto generated code of this method.

First create an instance of GroupingStore, a specialized store implementation which extends the ListStore that provides for grouping models by one of the available fields.

GroupingStore<Employee> employeeList = new GroupingStore<Employee>();  
employeeList.add(TestData.getEmployees());  
employeeList.groupBy("department");   

The groupBy method takes a property of your model by which you want to group your grid. In the example i have grouped the grid by 'department' property. You can change it to 'designation' property and see how it works.

Now define a list of ColumnConfig and a ColumnModel by using this list as before.
List<Columnconfig> configs = new ArrayList<Columnconfig>();

ColumnConfig column = new ColumnConfig();  
column.setId("name");  
column.setHeader("Employee Name");  
column.setWidth(200);  
configs.add(column);

column = new ColumnConfig("department", "Department", 150);  
column.setAlignment(HorizontalAlignment.LEFT);  
configs.add(column);

column = new ColumnConfig("designation", "Designation", 150);   
column.setAlignment(HorizontalAlignment.LEFT);  
configs.add(column);

column = new ColumnConfig("salary", "Slary", 100);  
column.setAlignment(HorizontalAlignment.RIGHT);  
final NumberFormat number = NumberFormat.getFormat("0.00");  
GridCellRenderer<Employee> checkSalary = new GridCellRenderer<Employee>() {  
public String render(Employee model, String property, ColumnData config, int rowIndex,  
int colIndex, ListStore<Employee> employeeList, Grid<Employee> grid) {  
double val = (Double) model.get(property);  
String style = val < 70000 ? "red" : "green";  
return "<span style='color:" + style + "'>" + number.format(val) + "</span>"; 
}  
};  
column.setRenderer(checkSalary);  
configs.add(column);

column = new ColumnConfig("joiningdate", "Joining Date", 100);  
column.setAlignment(HorizontalAlignment.RIGHT);  
column.setDateTimeFormat(DateTimeFormat.getShortDateFormat());  
configs.add(column);

final ColumnModel cm = new ColumnModel(configs); 

Create an instance of GroupView which groups the data based on the GroupStore. Then set it as the view of the Grid.

GroupingView view = new GroupingView();  
view.setForceFit(true);  
view.setGroupRenderer(new GridGroupRenderer() {  
public String render(GroupColumnData data) {  
String f = cm.getColumnById(data.field).getHeader();  
String l = data.models.size() == 1 ? "Item" : "Items";  
return f + ": " + data.group + " (" + data.models.size() + " " + l + ")";  
}  
});  

Grid<Employee> grid = new Grid<Employee>(employeeList, cm);  
grid.setView(view);  
grid.setBorders(true);

Here setForceFit is set true to auto expand the columns to fit the grid width and setGroupRenderer is used to create a heading for the groups.

Finally add the grid to the content panel.

ContentPanel cp = new ContentPanel();  
cp.setBodyBorder(false);  
cp.setHeading("Employee List");  
cp.setButtonAlign(HorizontalAlignment.CENTER);  
cp.setLayout(new FitLayout());  
cp.setSize(700, 420); 
cp.add(grid);  
RootPanel.get().add(cp);



Run the application and see how readable the grid is now. To view the live demo of this tutorial Click here.
gxtGridGrouping

How to create a simple Grid using GXT(Ext GWT)

GXT provides us with many powerful UI tools. One of this is the Grid. You can select which column you want to see or which you want to discard from the Grid at run time. Can sort the Grid by any column in both ascending and descending order. More over with the GridCellRenderer you can customized the look and feel of a cell. This tutorial describes every steps of creating a simple Grid using GXT in detail.
First create a new project named GxtGridExample and add GXT library in the project.  To show a list of data in the Grid you have to prepare the data first. In this tutorial i am going to show you a list of employee. So i need a Employee class which extends the BaseModel class of the GXT. Here is the code for the Employee class.
package com.ratul.GxtGridExample.client.model;
import java.util.Date;
import com.extjs.gxt.ui.client.data.BaseModel;

public class Employee extends BaseModel {
private static final long serialVersionUID = 1L;

public Employee() {
}
public Employee(String name, String department, String designation,double salary, Date joiningdate) {
set("name", name);
set("department", department);
set("designation", designation);
set("salary", salary);
set("joiningdate", joiningdate);
}
public Date getJoiningdate() {
return (Date) get("joiningdate");
}
public String getName() {
return (String) get("name");
}
public String getDepartment() {
return (String) get("department");
}
public String getDesignation() {
return (String) get("designation");
}
public double getSalary() {
Double salary = (Double) get("salary");
return salary.doubleValue();
}
public String toString() {
return getName();
}
}


Employee has 5 properties and to set the value of a property the set method is used. First parameter of the method is the property name and second is the value of that property. The class has also the getter method for each property.
Now populate a list of Employee in the TestData class.
package com.ratul.GxtGridExample.client;

import java.util.ArrayList;
import java.util.List;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.ratul.GxtGridExample.client.model.Employee;

public class TestData {

public static List<Employee> getEmployees()
{
  List<Employee> employees = new ArrayList<Employee>();
DateTimeFormat f = DateTimeFormat.getFormat("yyyy-mm-dd");
  employees.add(new Employee("Hollie Voss","General Administration","Executive Dir  ector",150000,f.parse("2006-05-01")));
  employees.add(new Employee("Emerson Milton","Information Technology","CTO",12000  0,f.parse("2007-03-01")));
  employees.add(new Employee("Christina Blake","Information Technology","Project M  anager",90000,f.parse("2008-08-01")));
  employees.add(new Employee("Heriberto Rush","Information Technology","Senior S/W  Engineer",70000,f.parse("2009-02-07")));
  employees.add(new Employee("Candice Carson","Information Technology","S/W Engine  er",60000,f.parse("2007-11-01")));
  employees.add(new Employee("Chad Andrews","Information Technology","Senior S/W E  ngineer",70000,f.parse("2008-02-01")));
  employees.add(new Employee("Dirk Newman","Information Technology","S/W Engineer"  ,62000,f.parse("2009-03-01")));
  employees.add(new Employee("Bell Snedden","Information Technology","S/W Engineer  ",73000,f.parse("2007-07-07")));
  employees.add(new Employee("Benito Meeks","Marketing","General Manager",105000,f  .parse("2008-02-01")));
  employees.add(new Employee("Gail Horton","Marketing","Executive",55000,f.parse("  2009-05-01")));
  employees.add(new Employee("Claudio Engle","Marketing","Executive",58000,f.parse  ("2008-09-03")));
  employees.add(new Employee("Buster misjenou","Accounts","Executive",52000,f.pars  e("2008-02-07")));

return employees;
}
}

You data is prepared now to place in a GXT Grid.
Go to the onModuleLoad method of GxtGridExample class. Remove all the auto generated code of this method.
First create a list of ColumnConfig and configure each column.

List<Columnconfig> configs = new ArrayList<Columnconfig>();

ColumnConfig column = new ColumnConfig();  
column.setId("name");  
column.setHeader("Employee Name");  
column.setWidth(200);  
configs.add(column);

column = new ColumnConfig("department", "Department", 150);  
column.setAlignment(HorizontalAlignment.LEFT);  
configs.add(column);

column = new ColumnConfig("designation", "Designation", 150);  
column.setAlignment(HorizontalAlignment.LEFT);  
configs.add(column);

column = new ColumnConfig("salary", "Slary", 100);  
column.setAlignment(HorizontalAlignment.RIGHT);  
final NumberFormat number = NumberFormat.getFormat("0.00");  
GridCellRenderer<Employee> checkSalary = new GridCellRenderer<Employee>() {  
public String render(Employee model, String property, ColumnData config, int rowIndex,  
int colIndex, ListStore<Employee> employeeList, Grid<Employee> grid) {  
double val = (Double) model.get(property);  
String style = val < 70000 ? "red" : "green";  
return "<span style='color:" + style + "'>" + number.format(val) + "</span>";   
}  
};  
column.setRenderer(checkSalary);  
configs.add(column);

column = new ColumnConfig("joiningdate", "Joining Date", 100);  
column.setAlignment(HorizontalAlignment.RIGHT);  
column.setDateTimeFormat(DateTimeFormat.getShortDateFormat());  
configs.add(column);

The setId method bind the column with a property of the model and the setHeader method set the column header. You can also set this property of the ColumnConfig by using the constructor.  For the salary column here i define a custom GridCellRenderer<Employee> and set it with the setRenderer method which set the color of the salary value either green or red by checking its value. The other methods are self explanatory.
Create a ListStore of Employee type and add the employee list created in the TestData class.


ListStore<Employee> employeeList = new ListStore<Employee>();  
employeeList.add(TestData.getEmployees());

Now create a ColumnModel with the column configurations defined above and a Grid of Type Employee.

ColumnModel cm = new ColumnModel(configs);
Grid<Employee> grid = new Grid<Employee>(employeeList, cm); 
grid.setStyleAttribute("borderTop", "none"); 
grid.setAutoExpandColumn("name"); 
grid.setBorders(true); 
grid.setStripeRows(true);

The setAutoExpandColumn is used to defined which column will be expanded automatically when you hide a column. Other methods are self identifying.
You are just one step away from running the code. Create a ContentPanel and add the Grid to the panel.
ContentPanel cp = new ContentPanel();  
cp.setBodyBorder(false);  
cp.setHeading("Employee List");  
cp.setButtonAlign(HorizontalAlignment.CENTER);  
cp.setLayout(new FitLayout());  
cp.setSize(700, 300); 
cp.add(grid);  
RootPanel.get().add(cp);



Run the application and check the magic of GXT Grid. To view the live demo of this tutorial Click here.
employeeList

Total Pageviews

Tags

Twitter Updates
    follow me on Twitter

    Followers