Lightweight GWT layouts

There is a tendency when programming GWT apps to use a lot of layout components. This might stem from the fact that all of the samples in the showcase use multiple LayoutPanels to get the controls laid out in a reasonable fashion.

This approach has several drawbacks:

  • the LayoutPanels can generate a whole bunch of HTML which takes a while to render
  • styling these layouts can be challenging because of the wide range of style tags in play
  • figuring out how the different panels interact can be challenging

One recommendation is to use HtmlContainer to define layout, and only use the widgety bits of GWT that add a lot of value. Here’s a super-simple example:

public class MyGwtEntryPoint implements EntryPoint {

     public void onModuleLoad() {
          HtmlContainer container = new HtmlContainer(getTemplate());
          container.add(new Button("Button 1"), "#tag1");
          container.add(new Button("Button 2"), "#tag2");
          container.add(new TextField<String>(), "#tag3");

          RootPanel.get().add(container);
     }

     private native String getTemplate() /*-{
          return [
              '<table border="1"><tr>',
              '<td rowspan="2" id="tag1" valign="top"></td>',
              '<td id="tag2"></td>',
              '<td id="tag3"></td>',
              '</tr></table>'].join("");
      }-*/;
}

This has a number of advantages: it’s lightweight, it’s easily styled, and the template itself can be written by a designer instead of having a programmer fiddle around with pixels.

There is one major disadvantage: any time that we’re putting HTML into classes feels like traveling back in time to 1999. The HTML is extremely difficult to maintain and requires a recompile and deploy in order to make changes. Unfortunately, that’s the boat that you’re stuck in with GWT anyway: if you don’t specify the HTML in your template, GWT is going to go ahead and do it for you one way or another.

I should be clear: the template should be minimal, providing only the basic structure with the simplest HTML that works. Any actual styling should of course be handled via CSS.

It should also be noted that for very simple applications, the HTML can actually go in the app’s HTML file and accessed via RootPanel. But that becomes less useful as soon as you have multiple “pages” in your GWT application.

It's only fair to share...
Share on FacebookGoogle+Tweet about this on TwitterShare on LinkedIn

Leave a Reply