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

38 comments:

Maksud September 7, 2009 at 11:31 PM  

Except for a typo, the tutorial worked like a charm. Thanks Mr. Zawoad.

Maksud September 8, 2009 at 12:41 AM  

I had some pain converting this grid into RPC call. I wanted to get the data from the RPC call. There is a problem with DateTimeFormat. It does not work on Server side. (RPC Servlet implementation). Instead use traditional date functions.

bekirgözde October 9, 2009 at 12:58 AM  

Hi! it's nice tutorial but I have a problem in public String render with;
String style = val < 70000 ? "red" : "green";
The style gives an error and it said;
"The local variable style is never read"

Besides, "< / employee>" which is placed at the end of the code what is the purpose? besides eclipse gives an error;
"Syntax error on token(s), misplaced construct(s)"

I couldn't placed anywhere and I remove it. The code successfully run and show the table with no colorful salary text.

Thanks!

Unknown October 9, 2009 at 6:25 PM  

Hi Bekir,
Sorry that the problem you are facing is caused by my fault :(
After the line
String style = val < 70000 ? "red" : "green";
now write this,
return "<span style='color:" + style + "'>" + number.format(val) + "</span>";
Now your table will show colorful salary text. And the </employee> is a typo. I have made a correction for this.
Thanks for pointing the problems. Cheers..

bekirgözde October 15, 2009 at 3:36 AM  

Thanks Ratul it's very usefull thing... An thanks for your reply.... and hi from Turkey!

amjed November 3, 2009 at 10:22 AM  

Excellent post Shams Zawoad, thanks for saving awful lot of my time :)
Please keep the good work up,

amjed November 3, 2009 at 11:15 AM  

@Maksud
Same here, DataTimeFormat does not work from the server context.
com.extjs.*.*.client.* works when called from client code.

Soln:
java.text.DateFormat f = new SimpleDateFormat("yyyy-mm-dd");

and put all the f.parse in
try{
}catch(ParseException e){}

Unknown November 3, 2009 at 7:12 PM  

Thanks Amjed for your inspiring comment...

Manish Gupta November 25, 2009 at 10:41 PM  

thanks ratual this nice tutoril ist help a lot every body who are new to gwt but there are some miss print in


code link rel="stylesheet" type="text/css" href="css/ext-all.css" />


it is link rel="stylesheet" type="text/css" href="css/gxt-all.css" /> thanks again

Unknown November 26, 2009 at 12:24 AM  

Thanks Manish for your comment.
Actually when i wrote this tutorial that time gxt-1.2.4 was available and in that version the css file name was ext-all.css. They have changed the file name in 2.0.1 version...
But i will surely change this..

Mohammed Hossain Doula December 22, 2009 at 6:16 AM  

It works fine for test data... But not for the RPC call if I want to get resultset from DataBase table... It would be different If you would have shown calling RPC... Thanks...

Unknown December 23, 2009 at 4:21 AM  

@Mohammed Hossain Doula:
I have worked with it and have a plan to write a tutorial about this. Just can't manage time. For now i can give you an idea.

If you use jdo, create an entity for a database table and a shadow model of the entity to show it in the gxt grid.
Fetch the entity list by a query and convert this to a list of that shadow model. Then add this model list to the gxt ListStore. Thats' all.

Dinakar May 15, 2010 at 8:19 AM  

did you have to implement the print preview functionality for the grid ? (showing records from all pages if you had multiple pages?

Unknown May 15, 2010 at 9:23 PM  

Sorry Dinakar i have not yet implemented the print preview functionality for grid.

Anonymous August 25, 2010 at 7:35 AM  

thanks for all.
I follow your example and i want to fill the grid by data from mysql without your class EmplyeeData.
for this i create a method in GWTServiceImpl named :

public List getEmployee()
...
List employees = new ArrayList();
rs = st.executeQuery(req1);
rs.last();
int count = rs.getRow();

rs.first();
for (int i = 0; i < count; i++) {
employees.add(new Employee(rs.getString("name"), rs.getString("department"),rs.getString("designation"), rs.getDouble("salary")));

rs.next();
}
return employees;
} catch (Exception ee) {
return employees1;
}
this methode return back List to the client

in the client
within the code i added :

final ListStore employeeList = new ListStore();

final AsyncCallback > callback = new AsyncCallback >() {

@Override
public void onFailure(Throwable caught) {
lblServerReply.setText("Communication failed");;
}

@Override
public void onSuccess(List result) {
employeeList.add(result);


}

};


getService().getEmployee(callback);

this call failed but if i make a concatination to String the call ==> Success

Please can you help me
Thanks

Unknown August 25, 2010 at 10:19 PM  

Use List<Employee> and ListStore<Employee>

Anonymous September 28, 2010 at 8:28 AM  

if it is possible to have the source code of this tutorial, it would be very helpful to me, because actually i find that some parts are missing in this tutorial. I followed all the steps mentioned above and the running result was not the same as you show... Anyone has an answer for me please

Unknown September 28, 2010 at 8:44 PM  

You will find the source code here
http://gxtexamplegallery.appspot.com/

abdeltn December 17, 2010 at 3:21 AM  

what about the print view functionality, i m searching to implement it on my grids. i saw it is implemented on smart gwt grids.

Anonymous March 23, 2011 at 3:18 AM  

I followed the same steps in this article, but I receive this error

Caused by: java.lang.RuntimeException: Deferred binding failed for 'com.extjs.gxt.ui.client.widget.grid.GridTemplates' (did you forget to inherit a required module?)

quelles sont les modifications que je dois effectuer

Help me please !!

Unknown March 23, 2011 at 3:30 AM  

in your project's gwt.xml file add this line

<inherits name='com.extjs.gxt.ui.GXT'/>

Anonymous October 24, 2011 at 3:07 AM  

I am geeeting this error
List cannot be resolved to a type
at line

List configs = new ArrayList();

Anonymous October 24, 2011 at 3:11 AM  

And this error in eclipse.
______________
The type new GridCellRenderer(){} must implement the inherited abstract method GridCellRenderer.render(Employee, String, ColumnData, int, int, ListStore, Grid)
__________________

Please help

Anonymous October 24, 2011 at 3:21 AM  

And this one

Columnconfig cannot be resolved to a type

Unknown October 24, 2011 at 7:31 PM  

Try with this
List<ColumnConfig> configs = new ArrayList<ColumnConfig>();

There is a typo in my code. It will be ColumnConfig not Columnconfig

jack March 3, 2012 at 4:01 AM  

Hi I have posted whatever I could after the casino like start up exp with GWT GXT and now settled or know the initial bit bout GWT GXT and put my initial fight with these 2 beasts at
http://gwt-gxt-java.blogspot.com.au/

It is simple but the similar names and no docs hs made it more difficult for new starter like me

My Query….
I plan to do a POC for my company’s website replace flash PHP prosql database
With GWT GXT plain java using spring (to give structure to java code) hibernate (db con pooling etc) oracle my confusion will I require the servlet part of it?

Are there any articles showing such integration?

Every one writes onModulload and the component or widget pops up….i have seen nothing beyond that any help appreciated
mail id anirudhghorpade@gmail.com

Thanh June 24, 2012 at 9:17 PM  

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);

where is cp.add(grid); and where to create it

Unknown June 24, 2012 at 9:39 PM  

@Thanh Le Dinh Hoai: If you do not add cp.add(grid); then the grid will not be shown in the page. The content panel (cp) is directly added to Rootpanel, not the grid.

Thanh June 25, 2012 at 10:48 PM  

i have a webservice create by asp.net + linq. So how to get data from my webservice to grid on gxt?

Thanh June 27, 2012 at 2:48 AM  

can any one help me? about get data from webservice

Anonymous August 23, 2012 at 7:22 AM  

thank your for this tutorial
I'm using gxt-3.0.1-GPL. Indeed, there are some diffrences between the latest version and the one used in this tutorial
so I want to know how can we save changes(reordering columns, show/hide a column) to the grid after refreshing the page or closing the browser

Rashik H December 26, 2012 at 11:20 PM  

I would like to know how to disable multi select in the grid.

I don't find selection model for the grid.

Please Suggest. !!!

Anonymous February 25, 2013 at 11:08 PM  

Hi Ratul

There is no information on the department method used in the ListFilter. Whats there in the method.Can you please post that too.

Thanks!

Zaenal May 22, 2013 at 7:50 PM  

excellent tutorial, It's works
but, how to create simple entity class if I use database MySQL,

before, my entity class:

public class User extends BaseModel{

//variable
private String name;
private String pass;

public User(){
}

public User(String Name, String Pass){
this.name = Name;
this.pass = Pass;
}

//Setter and Getter
public String getName() {
return name;
}

public void setName(String Name) {
this.name = Name;
}

public String getPass() {
return pass;
}

public void setPass(String password) {
this.pass = pass;
}

}

It's true or not, help me
Is there a lack in this code?
where should I add it?

Unknown April 10, 2014 at 4:23 AM  
This comment has been removed by the author.
Unknown April 10, 2014 at 4:25 AM  

Shams

I'have error here,

column.setAlign(HorizontalAlignment.LEFT);

It cannot allowed .setAlignment here.

Please help me.
I don't know which jar file u were used.??

Mohammed February 21, 2015 at 6:29 PM  

IS it possible to get a responsiveness using GXT?

Kesha's Experiences January 8, 2016 at 4:26 AM  

Is it possible to get responsiveness using GXT?
Can the columns be set as a percentage of the entire grid width ?

Total Pageviews

Tags

Twitter Updates
    follow me on Twitter

    Followers