Best GWT Libraries: Ext GWT (GXT) vs GWT-Ext vs SmartGWT

The Ext GWT, SmartGWT and GWT-Ext are the most used and cool widget frameworks on top of the GWT.

As of today the current versions of these libraries can be downloaded from here:

1. Ext GWT (GXT)

Ext GWT is a Java library for building rich internet applications with the Google Web Toolkit (GWT). It's built directly using GWT with no extra JavaScript library, just using pure GWT-ish Java code and an extensive gxt-all.css file. The output of this library is identical to that of GWT-Ext as it is also based on the ExtJS library, but GXT is lighter and faster than it's GWT-Ext counter-part.

Ext GWT has several licensing options available to fit a variety of needs including open source and commercial licenses. For more information, please visit the license page.

For eclipse IDE there is available a plugin to help developement  called Ext GWT Help Plugin. This one can be installed from the http://extjs.com/deploy/gxt-update-site.

2. SmartGWT

SmartGWT is a GWT wrapper framework on top of a JavaScript library. It allows you to not only utilize its comprehensive widget library for your application UI, but also tie these widgets in with your server-side for data management. Smart GWT is based on the powerful and mature SmartClient library, and it works in a similar way like GWT-Ext.

Smart GWT is compatible with GWT 1.5.3 , GWT 1.6.4, GWT 1.7.x and GWT 2.0.
 
There is available also a commercially licensed version of SmartGWT that includes Java Server side functionality, additional tools, and a classic commercial license in lieu of the LGPL. (showcase). An evaluation can be downloaded from here.
 
Here is presented  the comparison between different versions of SmartGWT library.
 
 
3. GWT-Ext

GWT-Ext is a quite advanced GWT wrapper framework on top of a JavaScript library. It helps tie together the functionality of the Google Web Toolkit and the widgets available in the ExtJS javascript library, which is very stylish, functionality rich and most of all performant. Too bad that's dead now!!!

GWT-Ext does not distribute ExtJS, which you need to include in your project. Note that GWT-Ext only supports ExtJS versions 2.0.2 or lower. You can download Ext 2.0.2 from here. Ext 2.0.2 has a variety of licensing options and LGPL 3.0 is one of them. The license file can be found in its distribution, or you can find it here.

It has also an extension library, called GWT-Ext-UX, developed by users like you :)

Here's a simple graphical representation of what I enumerated above:


4. Personal experience

I've used for developement the GWT-Ext and GXT libraries, so far.

The GWT-Ext is a very good, easy to understand and use. After it was "sacked" we had to find out a replacement.

The API of the SmartGWT was completly different (i.e. name of the methods, which do same thing, were complete different, either because of the javascript underneath, or just for the sake of it - we'll never know).

The GXT is a very good candidate for the migration from GWT-Ext, because lots of APIs are the same or very similar. It uses pure GWT principles making applications more efficient / compact; also, it uses the MVC (not MVP as I said earlier -- my bad!) pattern, but the events manipulation is quite different (Listeners instead of Handlers), though, this is acceptable, and even you have to pay for, it's worth it.

If I'd start from scratch the SmartGWT would be the choice. Only from looking at the SmartGWT showcase, this seems very rich in UI controls, and not only that, the server side has some good tools too. Also, with the latest versions the look and feel has improved a lot, and I would go with it, not only for fun and learning new stuff, but it seems a really good job.

Cheers!


Similar articles:
* JVM Web Framework Comparison

GXT 2.1 - Hidden toolbar don't layout the buttons after it's made visible

Problem:
I have a content panel that has set the accordion layout. The children panels have toolbar as top-component. First child-panel looks ok, but the others are wrong after expand (toolbar buttons are not correctly layout-ed).

Here's the test code:

public void testAccordionWithToolBar() {

    ContentPanel a = new ContentPanel(new AccordionLayout());
    a.setHeaderVisible(false);

    ContentPanel cp;
    cp = createChildPanel("child 1");
    a.add(cp);

    cp = createChildPanel("child 2");
    a.add(cp);

    cp = createChildPanel("child 3");
    a.add(cp);

    Window w = new Window();
    w.setLayout(new FitLayout());
    w.setHeading("Test Accordion");
    w.setSize(300, 300);
    w.add(a);
    w.show();
}

private ContentPanel createChildPanel(String title) {
    ContentPanel cp = new ContentPanel();
    cp.setHeading(title);

    /** add toobar as top-component of the child panel */
    ToolBar tb = new ToolBar();
    tb.setEnableOverflow(false);

    tb.add(new FillToolItem());
    tb.add(new Text("Buttons  "));

    Button b;

    b = new Button();
    b.setIcon(IconHelper.create("resources/images/default/dd/drop-add.gif"));
    tb.add(b);

    b = new Button();
    b.setEnabled(false); /** disabled button */
    b.setIcon(IconHelper.create("resources/images/default/dd/drop-no.gif"));
    tb.add(b);

    b = new Button();
    b.setIcon(IconHelper.create("resources/images/default/dd/drop-yes.gif"));
    tb.add(b);

    cp.setTopComponent(tb);

    return cp;
}

And here's the image with the bad result:



It seems that the problem is when something is collapsed, it gets hidden with display "none".

Actually, there is something wrong with the layout of the toolbar, when is not visible ... not strict related with the "expand" event, because I get wrong buttons when I have a TabPanel and I try to refresh the status (enabled/disabled) of the buttons from the background  TabItem, which is not visible.

 Note: This bad problem is also in GXT 2.0.4 !

Solution:
Don't worry if you have this problem, because -- HOOREY! -- I found the solution:

- First, you need to set:
   toolBar.setEnableOverflow(false);

to make the toolbar "non overflow"-able

- Secondly, you need to set:
   button.setMinWidth(22);

because when it's inserted in the toolbar, after this was rendered, the "insert(c, index)" is looking at the min-width of the button and if nothing is set then the default value (-1) is used, and bad result happens.

So, after you do these 2 things then the correct result is like below, a fully functional toolbar:



Cheers!

GWT - How to show the wait cursor for long tasks

In case you have a task that takes more than 2 seconds you need to signal to the user that he needs to wait a little longer than usual. This can be done in many ways, here, we are talking about the setting the cursor to a WAIT cursor.

For this reason we have wrote 2 static functions to set the cursor to wait and then to put it back when the long task is over.

public static void showWaitCursor() {
    DOM.setStyleAttribute(RootPanel.getBodyElement(), "cursor", "wait");
}

public static void showDefaultCursor() {
    DOM.setStyleAttribute(RootPanel.getBodyElement(), "cursor", "default");
}

Here are the possible types of the HTML cursors, which can be used in different cases:

 


Example of how to use the functions to change HTML cursor for long task:

/**
 * create the long task instance, which in our case extends:
 *   interface Function { execute(); } 
 */
final Task longTask = new Task();

/** shows the wait cursor */
showWaitCursor();

/** launch the long task in a separate thread */
DeferredCommand.addCommand (new Command() {
    @Override
    public void execute () {
        try {
            longTask.execute();
        } finally {
            /* when task finishes (successful, or with failure) set back the default cursor */
            showDefaultCursor();
        }
    }
});

That's pretty much all.

Cheers!

MONEY on THREAD - Personal Budget, Finance Application (free)

The application for personal bugeting, with a brilliant new idea to put Money on Thread has been released -- it's simple, maybe too simple -- if you are professional go with Microsoft Money or Quicken ... this one is for the rest of the world, like us (financial newborns).

So, are you tired of trying to keep your budget under control ?

Too much paper ? Too many computations ?

Too complicate tools that are trying to help you, but actually they puzzle you more?

If YES is the answer to all these questions, then your search has ended. You found here what you really wanted. Your life will become much easier with this tool.


Money on Thread is a simple way to keep your money tied very well on your personal thread, so no single penny can go away without tracking.

Money on Thread is simple, quick, and very good to keep your budget under control.

In a nutshel, this is a free simple application for personal finance, house budget, or household budget. You add, delete modify the trasactions that you usualy have (salary, morgage, rent, bank rate, car rate, credit cards due payments) on the "thread", and thus you can have a quick view when you might have some short cash, or not :-) It's very simple indeed!

There is support for the following languages: English, French, German, Spanish, Italian and Romanian (FR, GE, ES, and IT has been updated using the Google translator tool; so, please, be kind and send me corrections if something may sound "funny" !

You can download it from  HERE, at the Official Web Site !

Cheers!

GWT - Ideas to optimize GWT 2.0 applications

I hope we will improve the application itself (profile and fix using Firebug and SpeedTracer – other ideas are welcome) but we can also do other unrelated optimizations…

To reduce the number of round trips to the server, in addition to the good caching policy, we must take advantage of new GWT features, especially ClientBundle - this replaces ImageBundle.

A quick look at SpeedTracer shows GWT already optimizes 'png' into 'data:// ' stuff, which is embedded into the html:


It seems gif images are not inlined this way, yet. Maybe using ClientBundle instead of ImageBundle will solve this.

We should also take advantage of code splitting. It’s pretty easy to do – the complexity consists in identifying which parts can be run asynchronously. Probably the main page loaded after login and the main tabs “on click” handlers are good candidates.

For more info about all new features: http://timepedia.blogspot.com/2009/12/gwt-20-so-good-its-ridiculous.html. Interestingly, even if not related to optimization, the Ui Binder could help us if one day we decide to redesign the way the model entities are shared between the client and the server, and how the GUI is built.

Other ideas:

Code Splitting

As an AJAX app develops, the JavaScript part of it tends to grow, eventually to the point that downloading and installing the JavaScript code adds significant time to the application's startup. GWT's code splitter can speed up the application's startup by allowing the application to start running before all of its code is installed.

Compile Report
When programming in GWT, it can sometimes be difficult to understand the compiled output. This is especially true for users of Code Splitting: why are some fragments bigger, some smaller? Our answer to these questions are Compile Reports. Compile Reports let GWT programmers gain insight into what happens in their application during the compile: how much output their code leads to, what Java packages and classes lead to large JavaScript output, and how the code is split up during Code Splitting. Equipped with this information, programmers can then modify their application in a targeted way in order to reduce the size of the entire compiled application or the size of certain fragments.

Client Bundle
The resources in a deployed GWT application can be roughly categorized into resources to never cache (.nocache.js), to cache forever (.cache.html), and everything else (myapp.css). Client Bundles allow you to move resources from the everything-else category into the cache-forever category.

Lightweight Metrics
The Lightweight Metrics system is a tool to find key areas where latency may be noticeable to your end users. It has very little overhead, can report metrics on application load time and RPC calls, you can profile multiple GWT modules at the same time, and can be extended for your own measurement needs. The Debug Panel for GWT uses the Lightweight metrics system. It provides an easy way to collect metrics and test your GWT application.

So, currently, IMHO, we’re using GWT 2.0 just as we were driving a Ferrari at 30mph :-)) Let's push on the gas...


Cheers!

GWT Ext - HTML POST request to an URL

In case that we need to send a POST requet to a specific URL, within a GWT application that uses the free framework GWT-Ext, we can do it like in this sample code:

/**
* Send a POST call to a specified URL.
*
* @param baseUrl String where we want to send the POST HTML request
*
* @param urlParms list of UrlParam objects
*/
public static void post2URL(String baseUrl, List<UrlParam> urlParms) {
    ConnectionConfig conCfg = new ConnectionConfig();
    conCfg.setUrl(baseUrl);
    conCfg.setMethod(Connection.POST);

    /* URL parameters sent with every request */
    UrlParam[] arrParam;
    if (urlParms != null) {
        arrParam = urlParms.toArray(new UrlParam[0]);
    } else {
        arrParam = new UrlParam[] {};
    }

    /* create request object */
    RequestParam reqParam = new RequestParam();
    reqParam.setParams(arrParam);

    /* create connection and perform the request */
    Connection con = new Connection(conCfg);
    con.request(reqParam);
}

So, if we want to POST a request to an URL, i.e. /myApplication/Service, to add a new service to the server list of services, we can use the above defined function like in the following example:

String url = "/myApplication/Service"
List<UrlParam> urlParms = Arrays.asList (
    new UrlParam("operation", "add"),

    new UrlParam("name", "service 123")

);

post2URL (url, urlParms);

this is the same like "myApplication/Service?operation=add&name=Service+123".

More info: Developing with Ext GWT: Enterprise RIA Development

Cheers!

GXT - Show / hide the borders, individual, on sides of a panel

Do you need to play with the borders of the panel, individual, like top, left, bottom and right  ones.

The solution is valid only for the GXT (Ext GWT) library, and provide a new set of CSS classes, to override the ContentPanel, and add the helper functions in it.

- So, first step, here are the required CSS styles:

.my-border-top {
    border-top: 1px solid #99BBE8;
}

.my-border-bottom {
    border-bottom: 1px solid #99BBE8;
}

.my-border-left {
    border-left: 1px solid #99BBE8;
}

.my-border-right {
    border-right: 1px solid #99BBE8;
}

- The second step, is to use those CSS styles in our extended panel:

public MyPanel extends ContentPanel {

     public MyPanel () {
         /* remove all borders */
         setBodyBorders (false);
     }

    /* shows / hides the top side border */
     public void setTopBorder (boolean show) {
         setVisibleSideBorder (show, "left");
     }

    /* shows / hides the bottom side border */
    public void setBottomBorder (boolean show) {
        setVisibleSideBorder (show, "bottom");
    }

    /* shows / hides the left side border */
    public void setLeftBorder (boolean show) {
        setVisibleSideBorder (show, "left");
    }

   /* shows / hides the right side border */

    public void setRightBorder (boolean show) {
         setVisibleSideBorder (show, "right");
    }

   /* shows / hides the selected (left, right, top, bottom) side border */
   private void setVisibleSideBorder (boolean show, String sideName) {
       if (rendered) {
           El elem = fly(getStyleElement());
           if (show) {
               elem.addStyleName("my-border-" + sideName);
           } else {
               elem.removeStyleName("my-border-" + sideName);
           }
       } else {
           if (show) {
               addStyleName("my-border-" + sideName);
           } else {
               removeStyleName("my-border-" + sideName);
           }
       }

   }
}

- Now this is how we can use the provided solution:


MyPanel pane = new MyPanel ();
...
pane.setRightBorder (true);


so this panel has visible only the right-side border.

Cheers!

GWT - How to get parameters from the URL

Question:
Are you in the position that the simple URL that launches your application needs more information? like some extra parameters that we add usualy in any WEB application,

i.e.  h t t p : / / mysite . com ? parm1 = val1 & parm2 = val2
(spaces are added here to avoid having this example like a real clickable link).

So, how do we get this information within our GWT module / application ?

Answer:
 is quite simple, and it's present in the below helper static native function:

/**
* Gets the string with the parameters from the current URL.
*
* @return String containing the list of parameters from the URL
* in format: ?aaa=bbbb&vvvv=ccc
*/
public static native String getParamString() /*-{
     return $wnd.location.search;
}-*/;


So, the result of this is a string in the format "?parm1=val1&parm2=val2", which won't be a problem to parse and extract the list or parameters and their values, right ?

Cheers!

Mobile - iPhone Development Guide

To develop iPhone applications, you use Xcode, Apple’s first-class integrated development environment (IDE). Xcode provides all the tools you need to design your application’s user interface and write the code that brings it to life. As you develop your application, you run it on your computer, an iPhone, or an iPod touch.

This document describes the iPhone application development process. It also provides information about becoming a member of the iPhone Developer Program, which is required to run applications on devices for testing.

After you finish developing your iPhone application, you submit it to the App Store, the secure marketplace where iPhone OS users obtain their applications. However, you should test your application on a small set of users before publishing it to cover a wide variety of usage patterns and get feedback about your product. This document describes how to create a group of testers for your application and how to distribute it to them.

To take advantage of this document, you should be familiar with the iPhone application architecture, described in iPhone Application Programming Guide (from USEFUL LINKS). You should also be familiar with basic programming concepts.

After reading this document, you’ll have a basic understanding of the iPhone application development process. To enhance that knowledge, you should read the documents listed later in this introduction.

Software requirements: This requires to have an iPhone SDK 3.1 on Mac OS X 10.5.

If you’re interested in developing iPhone web applications, visit Safari Reference Library (from USEFUL LINKS).

Cheers!

Mobile - Android Development SDK

The Dev Guide is a practical introduction to developing applications for Android. It explores the concepts behind Android, the framework for constructing an application, and the tools for developing, testing, and publishing software for the platform.

The Dev Guide holds most of the documentation for the Android platform, except for reference material on the framework API.

The SDK can be downloaded from here Android Development SDK (from USEFUL LINKS).

After you have the SDK, begin by looking over the Dev Guide. If you want to start by getting a quick look at the code, the short Hello World tutorial walks you through a standard "Hello, World" application as it would be written for the Android platform. The Application Fundamentals document is a good place to start for an understanding of the application framework.
 
Cheers!

Mobile - Connected Java Mobile Gaming Development Gets a Boost

[Nokia has announced availability of SNAP Mobile Software Development Kit for easier creation of connected gaming using Java technology.]


Nokia has announced the availability of the latest Software Development Kit (SDK) for SNAP Mobile, its end-to end solution for connected mobile gaming in Java(TM) technology. The SNAP Mobile SDK 2.2 provides developers with a number of innovative tools to make it significantly easier to create connected mobile games. New features include a game template, skinable user interface framework, support for J2SE and Bot API. The SDK is available for download through Forum Nokia, the largest mobile development community worldwide, at http://www.forum.nokia.com/snapmobile.

"Nokia is committed to enhancing the mobile gaming experience and by adding these new elements to the SNAP Mobile SDK, we're making it faster and easier for developers to add connected gaming elements to their games," said Jonathan Sharp, Director, Games Strategy, Nokia. "Consumers expect more and more from their mobile games and this SDK will help developers deliver great Java games with superior connected gaming elements. We are working in close collaboration with our gaming partners to evolve the mobile gaming industry at large and together we can ensure that consumers get even better games."

The new game template provides a complete implementation for all required community functionality such as friends list and chat, with an interface that allows developers to either plug in existing game code, or to use as a basis for entirely new connected games. This template enables developers to concentrate on developing their game, not on the platform requirements, since most SNAP Mobile requirements are already in the game template.

With the user interface framework, developers can quickly manipulate a game's look and feel with easy to change XML. The UI framework includes a clean separation of controller logic which makes it easy to use with developers' existing UI frameworks. For example, PopCap Games' Chuzzle(TM) powered by SNAP Mobile is now available with new connected elements that enable players to compete globally for high scores. PopCap took their existing Chuzzle game and used the SNAP Mobile SDK 2.2 to quickly add connected functionality with only minimal redesign to the game's user interface. This is PopCap's first connected mobile game developed on a Nokia platform, with development ongoing for additional games expected to be available in 2009.

The SNAP Mobile SDK 2.2 also adds support for J2SE, enabling developers to design games with cross platform support. This means that SNAP Mobile games can also be created as a desktop applications or applets to run on PCs and web pages with the possibility to play against the same game's mobile version. For example, the N-Gage title Reset Generation uses the SNAP Mobile support for J2SE to enable players to compete against each other from a webpage and from their Nokia device.

The new Bot API helps developers deliver a better connected game experience as it guarantees that mobile players can find opponents online. If an opponent isn't immediately found online, the system will match players with a server based AI so they can play without having to wait for an opponent.


For more information on SNAP Mobile, please visit http://www.forum.nokia.com/snapmobile.

Cheers!

GXT - How to set tooltip for a grid cell

In the previous article we shown how to do the same thing, but for the framework GWT-Ext.

Now it's time to learn how to set the individual tooltips for each grid cell, not for the entire grid, with the GXT from ExtJS.

So, the drill is quite similar, but not exactly the same. We have to do 2 things:
 - first time we have to register a Tooltip Manager for the grid,  and
 - second time we define the renderer, which wraps the value in a "div" element with 2 special attributes "qtip" and "qtitle", like in the below code:

Grid grid = ...;

/** 1. register the tooltip manager for this grid */
new QuickTip(grid);

ColumnConfig cc = new ColumnConfig();
...
final String title = "Current Date";

/** 2. set the renderer for the grid cell */
cc.setRenderer(new GridCellRenderer<ModelData>() {
    @Override
    public Object render(ModelData model, String property,
           ColumnData config, int rowIndex,
           int colIndex, ListStore<ModelData> store,
           Grid< ModelData> grid) {
                String value = model.get (property);
                if (value != null) {
                     return "<div qtitle='" + Format.htmlEncode(title) + 
                            "' qtip='" + Format.htmlEncode(value) + 
                            "'>" + value + "</div>";
                }
                return value;
           }
});

So, assuming that the current column is a "date" called "Current Date" we want to display the tooltip with the name and value (Current Date / 2008 January 22 11:25:00 PM) and nothing when the cell value is null. The above code is doing exactly just this.

Cheers!

GWT - How to change title of the window browser

Let's say that you need to change programmatically the title of your WEB browser window.

For this you have to play with the GWT Document class, like in the below code, where we define a static function to help us:

import com.google.gwt.dom.client.Document;
...
public static void setBrowserWindowTitle (String newTitle) {
    if (Document.get() != null) {
        Document.get().setTitle (newTitle);
    }
}

It's not rocket science, but it's very cool to know simple tricks, which help you to do what you want.  Also, if you use a widgets framework like GXT (Ext GWT), SmartGWT, or GWT-Ext, be careful not to use their Document class, but the one from the GWT package, like it's shown above. Those new 'Document' classes not always behave the same :-) like the GWT.

Cheers!

GWT Ext - How to set tooltip for a grid cell

In the previous article we show how to set the background color of a grid cell. Now it's time to learn how to set the individual tooltips for each grid cell, not for the entire grid.

So, the drill is quite similar, we play with the CellMetaData from the renderer, like in the below code:

ColumnConfig cc = new ColumnConfig();
...
final String title = "Current Date";
cc.setRenderer(new Renderer() {
   public String render(Object value,
       CellMetadata cellMetadata, Record record,
       int rowIndex, int colNum, Store store) {
          String text = (value != null ? value.toString() : null);
          if (text != null) {
              String html_attr = "ext:qtitle='" + Format.htmlEncode(title) + "'";

              html_attr += " ext:qtip='" + Format.htmlEncode(text) + "'";
              cellMetadata.setHtmlAttribute(htmlAttr);
          }
          return text;
   } 
}); 

So, assuming that the current column is a "date" called "Current Date" we want to display the tooltip with the name and value (Current Date / 2008 January 22  11:25:00 PM) and nothing when the cell value is null. The above code is doing exactly just this.

Note: a solution for the exact problem, but using the GXT (Ext GWT) library, we have solved in this article.

Cheers!

GWT Ext - How to set the grid cell background color

Note: The similar problem we solved using the GXT library (Ext GWT) here.

So, again, we solve the whole trick in the rederer of the cell, and we play with the CellMetadata parameter.

ColumnConfig cc = new ColumnConfig();
final String bgColor = "yellow";
...

cc.setRenderer(new Renderer() {

   public String render(Object value,
      CellMetadata cellMetadata, Record record,
      int rowIndex, int colNum, Store store) {

          String htmlAttr = "style='background-color:" + bgColor + ";'";
          cellMetadata.setHtmlAttribute(htmlAttr);

          return (value != null ? value.toString() : null);
   }
});

Note: This code always puts the background color for grid cell. So, in the renderer code, you have to add the condition when you want to have the backgroud color set for that particular grid cell.

Cheers!

Andrei Gheorghe (TV star) beats 2 guests on LIVE show



UNBELIEVABLE: This is a real TV show that finishes with Andrei Gheorghe, a Romanian TV star, hitting both guests to his show. Imediately after that, he's been sacked from the Romanian TV channel 'Antena 1'.

And to top that, nowadays (January 2010) he's invited to be part of the Romanian Government, at the Finance Ministry :-)) Great job !

Cheers!

GWT - How to open a new window using an URL, not RPC ?

Question:
Do you need to open a new window, completly independent of your GWT application, by just passing an URL, whithout need to access the server through RPC?

Answer:
If you need to show the help window for your application, or spawn a new window, you have to define the following static function, and then call it in your GWT code, by passing the name of the window, and its URL. Of course, that on the server side you need to write a servlet that will process that URL, or JSP, or to have a static HTML page... but from the client point of view this is what you need to do.

Step 1. write the GWT static function:

/**
* Opens a new windows with a specified URL..
* 
* @param name String with the name of the window.
* @param url String with your URL.
*/
public static void openNewWindow(String name, String url) {
    com.google.gwt.user.client.Window.open(url, name.replace(" ", "_"),
           "menubar=no," + 
           "location=false," + 
           "resizable=yes," + 
           "scrollbars=yes," + 
           "status=no," + 
           "dependent=true");
}

Step 2. call it in your code like here:

String winUrl = GWT.getModuleBaseURL() + "help/";
String winName = "Testing Window";

openNewWindow (winName, winUrl);  /* spawn a new window - not popup */

I hope this will work fine for you, otherwise just write me your feedback, to fix the problems.

Cheers!

GXT - How to set the grid cell background color

Problem:
Do you need to set dynamically or programmatically the background color for some grid cells, let's say based on the value that they contain or other criteria ?

Note: The similar problem we solved using the GWT-Ext here.


Solution:
In a nutshell the solution is like you might be thinking too, the cell renderer. And doing this will get ready to write the code:

ColumnConfig typeCol = new ColumnConfig("Type");

typeCol.setRenderer(new GridCellRenderer<BaseModel>() {
   @Override 
   public Object render(BaseModel model, String property, 
                                   ColumnData config,
              int rowIndex, int colIndex,
              ListStore<BaseModel> store,
              Grid<BaseModel> grid) {

         Object value = model.get(property);         
         if (value != null)             
             return "<span " + 
                    "style='background-color:yellow;'>" + 
                    value.toString() + 
                    "</span>";
          return null;     
     }
});

The result of this code is like this, quite OK, but not perfect, the yellow background is set as long as the value is.


Another idea is to replace the span element with div, and the result will be like this


 we see the yellow background is spread more, but there is still lot of white space between cells.

And now,  the right solution is to use the "style" of the ColumnConfig object passed as parameter, like in this code:

ColumnConfig typeCol = new ColumnConfig("Type"); 

typeCol.setRenderer(new GridCellRenderer<BaseModel>() {    
    @Override
    public Object render(BaseModel model, String property, ColumnData config,
                         int rowIndex, int colIndex, ListStore<BaseModel> store,
                         Grid<BaseModel> grid) {
          config.style = "background-color:yellow;";
          Object value = model.get(property);
          return value;          
     } 
});

and the result is the expected one:
Cheers!