Showing posts with label Ext GWT. Show all posts
Showing posts with label Ext GWT. Show all posts

Working With GXT (Ext GWT) Grid : Add Filter Functionality

Yesterday I was looking for something new (new widgets, new functionality) in the latest GXT version (2.2.1) and found that, it is now providing grid filtering support. You can add MS Excel like filtering option in your application through this. I think it was the most demanded and expected feature from the GXT developers which can be highly utilized in Enterprise Reporting. I am going to describe how to add this functionality in GXT Grid.

Create a new project named GxtFilterGrid 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 GxtFilterGrid class and remove all the auto generated code of this method.

First create a list of ColumnConfig and a ColumnModel from this list.

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>() {
   @Override
   public Object render(Employee model, String property,
     com.extjs.gxt.ui.client.widget.grid.ColumnData config,
     int rowIndex, int colIndex, ListStore<Employee> store,
     Grid<Employee> grid) {
    double val = (Double) model.get(property);
    String style = val < 70000 ? "red" : "green";
    return ""
      + number.format(val) + "";

   }
  };
  column.setRenderer(checkSalary);
  configs.add(column);

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

  ColumnModel cm = new ColumnModel(configs);

Now create different types of filters like Numeric, String, Date, etc. Constructor of these filter classes takes the column name to bind the specific filter with a specific column.

NumericFilter numericFilter = new NumericFilter("salary");
StringFilter nameFilter = new StringFilter("name");
StringFilter designationFilter = new StringFilter("designation");
DateFilter dateFilter = new DateFilter("joiningdate"); 

You can also add a ListStore as a filtering option with the help of ListFilter. For adding a list filter, create a ListStore of ModelData or your own BaseModel class and add this as the source of ListFilter.

ListStore<ModelData> departmentStore = new ListStore<ModelData>();
departmentStore.add(departement("General Administration"));
departmentStore.add(departement("Information Technology"));
departmentStore.add(departement("Marketing"));
departmentStore.add(departement("Accounts"));
 //department method is stated later
ListFilter listFilter = new ListFilter("department", departmentStore);
listFilter.setDisplayProperty("departmentname");

Display Property of the ListFilter will be the key name of your model data. Now create a GridFilters instance and add all the filters created above with this instance.

GridFilters filters = new GridFilters();
filters.setLocal(true);
filters.addFilter(numericFilter);
filters.addFilter(nameFilter);
filters.addFilter(designationFilter);
filters.addFilter(dateFilter);
filters.addFilter(listFilter);

Finally create a ListStore of Employee Model and, a Grid from this ListStore and ColumnModel. Add the GridFilters instance as the Plugin of the Grid.

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

Grid<Employee> grid = new Grid<Employee>(employeeList, cm);
grid.setStyleAttribute("borderTop", "none");
grid.setAutoExpandColumn("name");
grid.setBorders(true);
grid.setStripeRows(true);
grid.getView().setForceFit(true);
grid.setColumnLines(true);
grid.addPlugin(filters);

ContentPanel cp = new ContentPanel();  
cp.setBodyBorder(false);  
cp.setHeading("Employee List With Filtering Option");  
cp.setButtonAlign(HorizontalAlignment.CENTER);  
cp.setLayout(new FitLayout());  
cp.setSize(700, 300); 
cp.add(grid);  
RootPanel.get().add(cp);
Here is the code of department method which is used previously.
private ModelData departement(String departement) {
  ModelData model = new BaseModelData();
  model.set("departmentname", departement);
  return model;
}

That's all. Run the project and the output will be like this

Working with DnD Framework of Ext GWT (GXT) : A Basic Example of Drag and Drop

DnD framework of Ext GWT is extremely powerful framework which supports drag and drop between two container, list view, grid, tree panel, tree grid and more over between heterogeneous components like list view to grid or grid to tree panel, etc. Here I am going to describe how you can drag a Html component and drop to a container.

Create a new project named BasicDnDExample and add GXT library in the project. Now go to the onModuleLoad method of BasicDnDExample class and remove all the auto generated code of this method.
First create a HorizontalPanel  and a LayoutContainer as the source container. Then add source components to the source container.

     HorizontalPanel hp = new HorizontalPanel();  
     hp.setSpacing(10);  
           
     final LayoutContainer sourceContainer = new LayoutContainer();  
     sourceContainer.setLayoutOnChange(true);  
     sourceContainer.setWidth(300);  
          
     List<Employee> employeeList = TestData.getEmployees();
     for(Employee employee : employeeList)
     {
        final Html html = new Html("<div style=\"font-size:11px; border: 1px solid #DDDDDD;float:left;margin:4px 0 4px  4px; padding:2px;width:220px;\">"+
          "<div style=\"color:#1C3C78;font-weight:bold;padding-bottom:5px;padding-top:2px;text-decoration:underline;\">"+employee.getName()+"</div>"+ 
          "<div style=\"color:green\">Department:"+employee.getDepartment()+"</div>"+ 
          "<div style=\"color:blue\">Designation:"+employee.getDesignation()+"</div>"+
          "<div style=\"color:black;padding-bottom:2px;\">Salary:"+employee.getSalary()+"</div>"+ 
          "</div>" ); 
        sourceContainer.add(html, new FlowData(3));  
                 
        DragSource source = new DragSource(html) {  
           @Override  
              protected void onDragStart(DNDEvent event) {  
                event.setData(html);  
                event.getStatus().update(El.fly(html.getElement()).cloneNode(true));  
             }  
        };  
                 
    }

Using the employee list I have created a Html component for each employee and add this to the source container. Then create DragSource with the component and set this as the Data of the DNDEvent.  You will find the code of Empoyee and TestData classes here.


Now create another LayoutContainer as the target container. Then create a DropTarget from the target container,  which identifies components that can receive data from a drag and drop operations. While the cursor is over a target, the target is responsible for determining if the drop is valid and showing any visual indicators for the drop.

           
    final LayoutContainer targetContainer = new LayoutContainer();  
    targetContainer.setLayoutOnChange(true);  
    targetContainer.setBorders(true);  
    targetContainer.setSize(300, 500); 

   DropTarget target = new DropTarget(targetContainer) {  
       @Override  
       protected void onDragDrop(DNDEvent event) {  
         super.onDragDrop(event);  
         Html html = event.getData();  
         targetContainer.add(html);  
       }  
  };  
  target.setOverStyle("drag-ok");

In the onDragDrop method you can define what you want to do after the element is dropped on the target. Here I have got the Html component from the DNDEvent and added the component in the target container.
Finally add the source and target container in the HorizontalPanel.

  hp.add(targetContainer);  
  hp.add(sourceContainer);  
  RootPanel.get().add(hp);

Output of this tutorial will be like this

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.

How to Use GXT XTemplate with ListView

XTemplate is a very useful class of GXT that supports auto-filling arrays, conditional processing with basic comparison operators, sub-templates, basic math function support, special built-in template variables, inline code execution and more. Here i am going to illustrate how to use XTemplate with a ListView to customize the look and feel of the ListView.

Create a new project named XTemplateExample and add GXT library in the project. To create a ListView at first you need a base model class and have to generate data for that model. In this tutorial i have used the same Employee model and TestData class for generating data which I have used in my previous blogs. You will find the code of these classes here.

Now go to the onModuleLoad method of XTemplateExample class. Remove all the auto generated code of this method.
First create a ListStore of Employee model , employeeList and add data to this store which was generated in the TestData class

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

Now Create a ListView of Employee type and set the employeeList as the store of the list view.
   ListView<Employee> lView = new ListView<Employee>();
   //getTemplate() returns the desired template
   lView.setTemplate(getTemplate());
   lView.setStore(employeeList);

   ContentPanel cp = new ContentPanel(); 
   cp.setBodyBorder(false); 
   cp.setHeading("Using XTemplate"); 
   cp.setButtonAlign(HorizontalAlignment.CENTER); 
   cp.setLayout(new FitLayout()); 
   cp.setSize(500, 420);
   cp.add(lView); 
   RootPanel.get().add(cp);

Here goes the definition of the getTemplate() method
private native String getTemplate() /*-{ 
       return ['<tpl for=".">', 
       '<div style="border: 1px solid #DDDDDD;float:left;margin:4px 0 4px  4px; padding:2px;width:220px;">',
       '<div style="color:#1C3C78;font-weight:bold;padding-bottom:5px;padding-top:2px;text-decoration:underline;">{name}</div>', 
       '<div style="color:green">Department:{department}</div>', 
       '<div style="color:blue">Designation:{designation}</div>',
       '<div style="color:black;padding-bottom:2px;">Salary:{salary}</div>', 
       '</div>', 
       '</tpl>', 
       ''].join(""); 
        
 }-*/;  

Properties of the Employee model are placed between {}. The style will be applied on every element of the employeeList. And the outcome of the work will be like this.


You can give your own look and feel by simply changing the CSS.


Getting Started with GXT (Ext GWT) Chart : Crate a Simple Horizontal Bar Chart

Ext GWT is providing us a very handy Chart library based on Open Flash Chart. Here you will find a step by step detail description about creating a simple horizontal bar chart using the GXT chart library.

Create a new project named GXTBascicChart and add GXT library in the project. Go to the GXTBascicChart.gwt.xml file and add this line

<inherits name='com.extjs.gxt.charts.Chart'/>

Now go to the directory where you have extracted the GXT library. In the resource folder you will find all the resources for using GXT. Copy the chart and flash folders in the war folder of you application.

Go to the onModuleLoad method of GXTBascicChart class and remove all the auto generated code of this method. Create a Content Panel to place the chart
ContentPanel cp = new ContentPanel();  
cp.setHeading("Horizontal Bar chart");  
cp.setFrame(true);  
cp.setSize(550, 400);  
cp.setLayout(new FitLayout());

Now create a Chart component by providing the location of the open flash chart Shockwave file which resides in the chart folder.
String url = "chart/open-flash-chart.swf";  
final Chart chart = new Chart(url);



Set a Chart Model for the chart object and add this to the Content Panel
chart.setBorders(true);  
chart.setChartModel(getHorizontalBarChartModel());  
cp.add(chart);      
RootPanel.get().add(cp);

The Chart Model is responsible for the chart title, axes, legends, labels, and draw-able elements in your chart. Here is the getHorizontalBarChartModel method
public ChartModel getHorizontalBarChartModel() 
{ 
  //Create a ChartModel with the Chart Title and some style attributes
  ChartModel cm = new ChartModel("Students by Department", "font-size: 14px; font-family:      Verdana; text-align: center;");
 
  XAxis xa = new XAxis();
  //set the maximum, minimum and the step value for the X axis
  xa.setRange(0, 200, 50);  
  cm.setXAxis(xa);
  
  YAxis ya = new YAxis();
  //Add the labels to the Y axis  
  ya.addLabels("CSE", "EEE", "CE", "ME","CHE");  
  ya.setOffset(true);  
  cm.setYAxis(ya);

  //create a Horizontal Bar Chart object and add bars to the object  
  HorizontalBarChart bchart = new HorizontalBarChart();  
  bchart.setTooltip("#val#Students");  
  bchart.addBars(new HorizontalBarChart.Bar(60, "#ffff00")); 
  //different color for different bars 
  bchart.addBars(new HorizontalBarChart.Bar(180, "#0000ff"));  
  bchart.addBars(new HorizontalBarChart.Bar(180, "#00ff00"));  
  bchart.addBars(new HorizontalBarChart.Bar(120, "#ff0000"));
  bchart.addBars(new HorizontalBarChart.Bar(120, "#333ccc"));

  //add the bchart as the Chart Config of the ChartModel
  cm.addChartConfig(bchart);       
  cm.setTooltipStyle(new ToolTip(MouseStyle.FOLLOW));  
  return cm;  
}

And here is the last step before running your application.
Go to the GXTBascicChart.html file and add the following line in the head section
<script language='javascript' src='flash/swfobject.js'></script>
That's all. Run the application and the output will be like this

How to Create an Editable TreeGrid in GXT(Ext GWT)

In our project I need to add the editable functionality with the GXT TreeGrid. Here I am going to share my experience about how to create an editable TreeGrid.

You may have already known that to build a TreeGrid the tree node objects must possess the functionality of BaseTreeModel of GXT. I have used the same EmployeeTreeNode and Folder class for leaf and parent nodes that i used in my previous blogs about GXT TreePanel. And in the TestData class i have populated the data to build the TreeGrid. You will find the code for these classes here.
(If you are new in GWT and GXT read my blogs about creating a new project in gwt and add GXT library)

First create a root object named model of the Folder class from TestData.getTreeModel() method.

Folder model = TestData.getTreeModel();
Then create a TreeStore object,store from this model and add data to the store
TreeStore<ModelData> store = new TreeStore<ModelData>();
store.add(model.getChildren(), true);

Now the time for defining ColumnConfig objects. First create a ColumnConfig, name and set a TextField as the editor of this object.
ColumnConfig name = new ColumnConfig("name", "Name", 100);
name.setRenderer(new TreeGridCellRenderer<ModelData>());
TextField<String> text = new TextField<String>();
text.setAllowBlank(false);
name.setEditor(new CellEditor(text));

The second column is the salary column so you can set a NumberField as the editor for this column.
ColumnConfig salary = new ColumnConfig("salary", "Salary", 100);
salary.setEditor(new CellEditor(new NumberField()));

In my example the third column is the joining date column. So you have to set a DateField as the editor for this column. For this first create a DateField object dateField and set the display format of the field. Then create a ColumnConfig object date and set the dateField as the editor of the date.
DateField dateField = new DateField();  
dateField.getPropertyEditor().setFormat(DateTimeFormat.getFormat("MM/dd/y"));
     
ColumnConfig date = new ColumnConfig("joiningdate", "Joining Date", 100); 
date.setAlignment(HorizontalAlignment.RIGHT);
date.setEditor(new CellEditor(dateField));  
date.setDateTimeFormat(DateTimeFormat.getMediumDateFormat());


Now create a ColumnModel from these three ColumnConfig objects.
ColumnModel cm = new ColumnModel(Arrays.asList(name, salary, date));

From the ColumnModel and TreeStore create an EditorTreeGrid object and set some property of the object.
EditorTreeGrid<ModelData> editorTreeGrid = new EditorTreeGrid<ModelData>(store,cm);
editorTreeGrid.setClicksToEdit(ClicksToEdit.TWO);
editorTreeGrid.setBorders(true);
editorTreeGrid.setSize(400, 400);
editorTreeGrid.setAutoExpandColumn("name");
editorTreeGrid.setTrackMouseOver(false);
The setter methods are self explanatory.

Finally create a ContentPanel and add the editorTreeGrid in this panel.
ContentPanel cp = new ContentPanel();
cp.setBodyBorder(false);
cp.setHeading("Cell TreeGrid Editing (2-Clicks)");
cp.setButtonAlign(HorizontalAlignment.CENTER);
cp.setLayout(new FitLayout());
cp.setFrame(true);
cp.setSize(600, 300);
cp.add(editorTreeGrid);
RootPanel.get().add(cp);
To view the live demo of this tutorial Click here.
The output will be like this

How to Create a Basic TreeGrid using GXT(Ext GWT)

When you want to display hierarchical data tree grid will be the right choice for this. GXT TreeGrid is a very powerful UI component which provides us with some wonderful functionality like row editor, row number, widget render etc. Here i present you the way of creating a basic TreeGrid in detail.

Create a new project named GxtBasicTreeGrid and add GXT library in the project. The tree node objects must possess the functionality of BaseTreeModel of GXT. I have used the same EmployeeTreeNode and Folder class for leaf and parent nodes that i used in my previous blogs about GXT TreePanel. And in the TestData class i have populated the data to build the TreeGrid. You will find the code for these classes here.

First create a root object named model of the Folder class from TestData.getTreeModel() method and create a TreeStore object,store from this model.
Folder model = TestData.getTreeModel();

TreeStore<ModelData> store = new TreeStore<ModelData>();
store.add(model.getChildren(), true);



Now define three ColumnConfig objects and create a ColumnModel from these objects.
ColumnConfig name = new ColumnConfig("name", "Name", 100);
name.setRenderer(new TreeGridCellRenderer<ModelData>());

 ColumnConfig salary = new ColumnConfig("salary", "Salary", 100);

 ColumnConfig date = new ColumnConfig("joiningdate", "Joining Date", 100);

 ColumnModel cm = new ColumnModel(Arrays.asList(name, salary, date));

Create a TreeGrid, treeGrid from the TreeStore, store and ColumnModel, cm. Then set some property of the treeGrid. Finally create a ContentPanel and add the treeGrid to this panel.
TreeGrid<ModelData> treeGrid = new TreeGrid<ModelData>(store, cm);
treeGrid.setBorders(true);
 treeGrid.getStyle().setLeafIcon(ICONS.user_add());
 treeGrid.setSize(400, 400); 
 treeGrid.setAutoExpandColumn("name");
 treeGrid.setTrackMouseOver(false);

 ContentPanel cp = new ContentPanel();
 cp.setBodyBorder(false);
 cp.setHeading("TreeGrid");
 cp.setButtonAlign(HorizontalAlignment.CENTER);
 cp.setLayout(new FitLayout());
 cp.setFrame(true);
 cp.setSize(600, 300);
 cp.add(treeGrid);
 RootPanel.get().add(cp);

Run the application and the output will be like this.

basicTreeGrid

To view the live demo of this tutorial Click here.

An Example Gallery of GXT(Ext GWT)

After written some blogs about GXT Grid and Tree I planned for merging all those in a single application. Beside this I want to test JDO in Google App Engine. As a result of this I have made a tiny application and deployed in the Google App Engine. Ext GWT (GXT) Example Gallery. I will be very pleased if you visit the site and give your valuable comment.

You can also check out the latest code of the project from Google svn by running this command

svn checkout http://gxtexamplegallery.googlecode.com/svn/trunk/ gxtexamplegallery-read-only





Add Context Menu with GXT(Ext GWT) TreePanel

Context Menu is frequently used with tree if you want to present a very user friendly interface to user like add,delete or enable,disable a tree node. Here i show you how you can add a context menu with add and delete menu items with GXT TreePanel very easily.
Create a new project named GxtContextMenuTree and add GXT library in the project. The tree node objects must possess the functionality of BaseTreeModel of GXT. I have used the same EmployeeTreeNode and Folder class for leaf and parent nodes that i used in my previous blogs related to GXT TreePanel. And in the TestData class i have populated the data to build the tree. You will find the code for these classes here.  Create a new package model under the client package and place the EmployeeTreeNode and Folder class there.



Now remove all the auto generated code from the GxtContextMenuTree class which is the entry point class of your project.  Go to the onModuleLoad  method of the class and first create a root node of the tree. Then create a TreeStore, store and add data to this store from the root node. Now create a TreePanel, tree from this store and set some property of the tree.
final Folder rootNode = TestData.getTreeModel();

final TreeStore<ModelData> store = new TreeStore<ModelData>();
store.add((List) rootNode.getChildren(), true);

final TreePanel<ModelData> tree = new TreePanel<ModelData>(store);
tree.setDisplayProperty("name");
tree.getStyle().setLeafIcon(ICONS.user_add());
tree.setWidth(250);


Now create a gxt Menu and add two MenuItem insert and remove with the menu.
Menu contextMenu = new Menu();
contextMenu.setWidth(140);

MenuItem insert = new MenuItem();
insert.setText("Insert Item");
insert.setIcon(ICONS.add());
contextMenu.add(insert);

MenuItem remove = new MenuItem();
remove.setText("Remove Selected");
remove.setIcon(ICONS.delete());
contextMenu.add(remove);

What you want to do by clicking on these menu items, just write them in the addSelectionListener method of the MenuItem. Then set the menu to the tree as a context menu by setContextMenu method of the TreePanel.
insert.addSelectionListener(new SelectionListener<MenuEvent>() {
public void componentSelected(MenuEvent ce) {
ModelData folder = tree.getSelectionModel().getSelectedItem();
if (folder != null) {
Folder child = new Folder("Add Child " + count++);
store.add(folder, child, false);
tree.setExpanded(folder, true);
}
}
});

remove.addSelectionListener(new SelectionListener<MenuEvent>() {
public void componentSelected(MenuEvent ce) {
List<ModelData> selected = tree.getSelectionModel().getSelectedItems();
for (ModelData sel : selected) 
{
store.remove(sel);
}
}
});

tree.setContextMenu(contextMenu);
RootPanel.get().add(tree);

In the addSelectionListener method of the insert menu item i have written the code for adding a Folder node with the selected node and in the same method of the remove menu item code for removing a list of selected nodes. To view the live demo of this tutorial Click here.

contextMenuTree

Add Filter Functionality with GXT(Ext GWT) TreePanel

In my previous blog i have articulated how you can create a basic tree using the GXT TreePanel. In the next few blogs i will try to write about some marvelous features which can be easily integrated with TreePanel. Here i state how to add filter functionality with TreePanel.

Create a new project named GxtFilterTree and add GXT library in the project. The tree node objects must possess the functionality of BaseTreeModel of GXT. I have used the same EmployeeTreeNode and Folder class for leaf and parent nodes that i used in my previous blog. And in the TestData class i have populated the data to build the tree. You will find the code for these classes here.

Go to the onModuleLoad method of GxtFilterTree class. Remove all the auto generated code of this method. Now create a TreeLoader, loader.

TreeLoader<ModelData> loader = new BaseTreeLoader<ModelData>(
  new TreeModelReader<List<ModelData>>());

BaseTreeLoader is default implementation of the TreeLoader interface which also extends the functionality of BaseLoader. Then create TreeStore, store by using the loader and create a TreePanel, tree with the store. Pass the root of the tree to the loader.load method as a load configuration which loads data using the configuration. You can get the root node from getTreeModel method of TestData class.




TreeStore<ModelData> store = new TreeStore<ModelData>(loader);
TreePanel<ModelData> tree = new TreePanel<ModelData>(store);
tree.setAutoLoad(true);
tree.setDisplayProperty("name");
tree.setWidth(250);
tree.setIconProvider(new ModelIconProvider<ModelData>() {
  public AbstractImagePrototype getIcon(ModelData model) {
    if (((TreeModel) model).isLeaf()) {
      return ICONS.user_add();
    }
    return null;
  }
});
loader.load(TestData.getTreeModel());

setAutoLoad method sets whether all children should automatically be loaded recursively. Other setter methods of TreePanel are self explanatory.

Now the time for creating a StoreFilterField and bind this to the store.
StoreFilterField<ModelData> filter = new StoreFilterField<ModelData>() {
  @Override
  protected boolean doSelect(Store<ModelData> store,
  ModelData parent, ModelData record, String property,
  String filter) {
    // only match leaf nodes
    if (record instanceof Folder) { 
      return false;
    }
    String name = record.get("name");
    name = name.toLowerCase();
    if (name.startsWith(filter.toLowerCase())) {
      return true;
    }
    return false;
  }
};
filter.bind(store);

StoreFilterField can filter any Store implementation. You just have to implement the doSelect method this class. Here i have matched only the leaf node.

You are just one step behind to run the application. Create a panel to add the filter and the tree and add that panel to the RootPanel. That’s all. Run the application and check the filter functionality.
VerticalPanel panel = new VerticalPanel();
panel.addStyleName("x-small-editor");
panel.setSpacing(8);
panel.add(new Html("<span class=text>Enter a search string such as 'dirk'</span>"));
panel.add(filter);
panel.add(tree);
RootPanel.get().add(panel);

}
To view the live demo of this tutorial Click here.

treeWithFilterFunc

How to Create a Simple Tree Using GXT(Ext GWT) TreePanel

TreePanel is another powerful UI tools provide by GXT.  It has expand-collapse functionality. You can add context menu or can add filter functionality with the TreePanel very easily. Here i describe every steps of creating a simple basic Tree using GXT in detail.

First create a new project named GxtBasicTree and add GXT library in the project. The tree node objects must possess the functionality of BaseTreeModel of GXT. In my example the leaf node objects are of EmployeeTreeNode class and parent node objects are of Folder class. Both of the classes extend BaseTreeModel class. Here is the code for the Employee class.

package com.ratul.GxtBasicTree.client.model;

import java.util.Date;

import com.extjs.gxt.ui.client.data.BaseTreeModel;

public class EmployeeTreeNode extends BaseTreeModel {
 private static final long serialVersionUID = 1L;

public EmployeeTreeNode() {
  }

  public EmployeeTreeNode(String name, double salary, Date joiningdate) {
    set("name", name);
    set("salary", salary);
    set("joiningdate", joiningdate);
  }

  public Date getJoiningdate() {
    return (Date) get("joiningdate");
  }

  public String getName() {
    return (String) get("name");
  }

  public double getSalary() {
    Double salary = (Double) get("salary");
    return salary.doubleValue();
  }
  public String toString() {
    return getName();
  }
}
As i have said previously the objects of the Folder class can be parent node for the Tree. So this class should have the functionality of adding children nodes. The constructor with a String and an Array of BaseTreeModel object serves the purpose. Here is the code for the Folder class.



package com.ratul.GxtBasicTree.client.model;

import java.io.Serializable;

import com.extjs.gxt.ui.client.data.BaseTreeModel;

public class Folder extends BaseTreeModel implements Serializable {
 private static final long serialVersionUID = 1L;
private static int ID = 0;
  
  public Folder() {
    set("id", ID++);
  }

  public Folder(String name) {
    set("id", ID++);
    set("name", name);
  }

  public Folder(String name, BaseTreeModel[] children) {
    this(name);
    for (int i = 0; i < children.length; i++) {
      add(children[i]);
    }
  }

  public Integer getId() {
    return (Integer) get("id");
  }

  public String getName() {
    return (String) get("name");
  }

  public String toString() {
    return getName();
  }
}

Now populate a root node containing all the child nodes by using the above two classes in the getTreeModel methodh of the TestData class.
package com.ratul.GxtBasicTree.client;

import com.google.gwt.i18n.client.DateTimeFormat;
import com.ratul.GxtBasicTree.client.model.Employee;
import com.ratul.GxtBasicTree.client.model.Folder;

public class TestData {

  public static Folder getTreeModel() 
  {
     DateTimeFormat f = DateTimeFormat.getFormat("yyyy-mm-dd");
  Folder[] folders = new Folder[] {
   new Folder("General Administration", new Folder[] {
    new Folder("General Manager", new EmployeeTreeNode[] {
     new EmployeeTreeNode("Hollie Voss", 150000, f.parse("2006-05-01")),
     new EmployeeTreeNode("Heriberto Rush", 150000,f.parse("2007-08-01")), }),
    new Folder("Executive", new EmployeeTreeNode[] {
     new EmployeeTreeNode("Christina Blake", 45000,f.parse("2008-11-01")),
     new EmployeeTreeNode("Chad Andrews", 45000, f.parse("2008-07-01")), }), }),
 
   new Folder("Information Technology",new Folder[] {
    new Folder("Senior S/W Engineer",new EmployeeTreeNode[] {
     new EmployeeTreeNode("Dirk Newman", 70000,f.parse("2007-08-21")),
     new EmployeeTreeNode("Emerson Milton",72000,f.parse("2009-05-07")),
     new EmployeeTreeNode("Gail Horton", 680000,f.parse("2008-05-01")), }),
    new Folder("S/W Engineer",new EmployeeTreeNode[] {
     new EmployeeTreeNode("Claudio Engle", 50000,f.parse("2007-02-01")),
     new EmployeeTreeNode("Buster misjenou",52000,f.parse("2009-06-10")),
     new EmployeeTreeNode("Bell Snedden", 50000,f.parse("2008-12-01")),
     new EmployeeTreeNode("Benito Meeks", 55000,f.parse("2006-05-01")), }), }),
 
   new Folder("Marketing", new Folder[] { 
    new Folder("Executive",new EmployeeTreeNode[] {
     new EmployeeTreeNode("Candice Carson", 50000, f.parse("2007-08-21")),
     new EmployeeTreeNode("Mildred Starnes", 50000,f.parse("2008-05-01")),
     new EmployeeTreeNode("Claudio Engle", 50000, f.parse("2009-06-15")), }), }), 
  };

  Folder root = new Folder("root");
  for (int i = 0; i < folders.length; i++) {
   root.add((Folder) folders[i]);
  }

  return root;
  }
}
You data is now ready to create a simple Tree. Go to the onModuleLoad method of GxtBasicTree class. Remove all the auto generated code of this method. Now first create a root object named model of the Folder class from TestData.getTreeModel() method and create a TreeStore object,store from this model.
public static final ExampleIcons ICONS = GWT.create(ExampleIcons.class);
public void onModuleLoad() 
{
       Folder model = TestData.getTreeModel();  
     
       TreeStore<ModelData> store = new TreeStore<ModelData>();  
       store.add(model.getChildren(), true);  
 
Now create a TreePanel, tree from this store and set display name, width and style of the tree.
final TreePanel<ModelData> tree = new TreePanel<ModelData>(store);  
       tree.setDisplayProperty("name");  
       tree.setWidth(250);  
       tree.getStyle().setLeafIcon(ICONS.user_add());
The two button expand and collapse provide the expand and collapse functionality by simple calling the tree.expandAll() and tree.collapseAll() method.
ButtonBar buttonBar = new ButtonBar();  
       Button expand = new Button("Expand All"); 
       Button collapse = new Button("Collapse All"); 
       expand.addSelectionListener(new SelectionListener<ButtonEvent>() {  
       public void componentSelected(ButtonEvent ce) {  
           tree.expandAll();  
         }  
       });
       
       collapse.addSelectionListener(new SelectionListener<ButtonEvent>() {  
        public void componentSelected(ButtonEvent ce) {  
            tree.collapseAll();  
          }  
        });
       buttonBar.add(expand);
       buttonBar.add(collapse);
        
       RootPanel.get().add(buttonBar);
       RootPanel.get().add(tree);
       
 }


That's all. Run it and check the functionality of the simple tree. To view the live demo of this tutorial Click here.

Working with GXT(Ext GWT) Grid : Add Local Pagination Functionality

In my previous blog i have described how to create a simple Grid of GXT.  I have a plan to write a series of blog about other useful functionalities which can be added to the Grid. Here i write down the way of adding local pagination functionality with the Grid.

Create a new project named GxtPagingExample and add GXT library in the project. To create a grid at first you need a base model class and have to generate data for that model. In this tutorial i have used the same Employee model and TestData class for generating data which i used in my previous blog. You will find the code of these classes there.

Now go to the onModuleLoad method of GxtPagingExample class. Remove all the auto generated code of this method. First create an instance of PagingModelMemoryProxy which is a specialized DataProxy that supports paging when the entire data set is in the memory.

PagingModelMemoryProxy proxy = new PagingModelMemoryProxy(TestData.getEmployees());
   PagingLoader loader = new BasePagingLoader(proxy);
   loader.setRemoteSort(true);
   ListStore<Employee> employeeList = new ListStore<Employee>(loader);  
BasePagingLoader is an implementation of the PagingLoader interface which loads data using the proxy.If remote sort is enable then it will allow you to sort between the whole data set otherwise the sorting will be done only between the viewable data set. Then create a ListStore of Employee type.




Now create a PagingToolBar widget then bind it with the loader. It takes the page size in the constructor.
final PagingToolBar toolBar = new PagingToolBar(5);
   toolBar.bind(loader);
   loader.load(0, 5);
The arguments of the load method of PagingLoader are the begin index and page size.

Create a list of ColumnConfig and define each column. Then create a grid and add the grid and the PagingToolBar in a panel.

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

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

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);  
cp.setBottomComponent(toolBar);
RootPanel.get().add(cp);

Explanation of the above code is written here.
That's all. Run the application and test the pagination functionality. To view the live demo of this tutorial Click here.

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

Keep yourself updated with the latest GWT technologies (gwt , app engine and gxt)

It’s been long since i have worked with GWT. I have been very busy with my scheduled tasks and can not afford to spend time on investing the features of this outstanding web technology.  Today i have sit with it and found that everything is required to be updated. The SDK for GWT, Google App Engine and the Ext GWT Library (The world is running fast?huh). I have updated all these and  here i write down the procedure for eclipse 3.4.

Download GWT version 1.7 from here and Google App Engine SDK 1.2.2 from here. Unzip the folders then open the Window->Preference window of eclipse.

Expand the Google menu from the left tree menu.  Select the Web Toolkit menu and it will show you the previous version of GWT. Click on the Add Button and select the unzipped folder as the installation directory.  Now check the latest SDK so that it will be the default SDK for the newly created projects.

gwtupdate1

 

Now select the App Engine menu and follow the steps stated above to add the latest version of the SDK.

You are now ready to use the latest version of GWT and Google App Engine SDK.

To use the latest version of Ext GWT library download this from here and follow my previous blog about how to use it in your GWT project.

How to use Ext GWT(GXT) in Eclipse 3.4 to create a rich internet application

Ext GWT is a Java library for building rich internet applications with the Google Web Toolkit (GWT). If you have started working with GWT you will find the Ext GWT library very helpful for its high performance and customizable UI widgets. Here I describe you how to use this library in your GWT project.

First of all download Ext GWT 1.2.4 SDK, the latest stable version of this library and extract it.

Now Create a GWT project by following the steps I have described in my previous blog. Follow the steps to add gxt.jar to the project.

->Right click on project and select the properties menu..
->Select Java Build Path.
->Select Libraries tab.
->Click on Add External JARS and select gxt.jar. (You will find this jar file inside the folder where you have extracted the library previously. )



Now change the your_project_name.gwt.xml file. Add the following line in this file.

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





Here goes the tricky part. You will find a folder named resources in the extracted folder. This contains the css and images used in this library. Copy the css and images folder in the war folder of your application. Now add the following stylesheet to your host page.

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


And remember Ext GWT requires no doctype or the following doctype (quirksmode).

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">


That's all. You are now ready to use the Ext GWT library to enhance your application.

Total Pageviews

Tags

Twitter Updates
    follow me on Twitter

    Followers