gwt

GWT Datagrid Example

In this example we will learn about GWT Datagrid.

Tools and technologies used in this example are Java 1.8, Eclipse Lune 4.4.2, Eclipse GWT Plugin 2.6.

1. GWT

GWT is a development toolkit for building and optimizing complex browser-based applications. Its goal is to enable productive development of high-performance web applications without the developer having to be an expert in browser quirks, XMLHttpRequest, and JavaScript. GWT is used by many products at Google, including AdWords, AdSense, Flights, Hotel Finder, Offers, Wallet, Blogger. It’s open source, completely free, and used by thousands of developers around the world.

2. DataGrid

DataGrid is a tabular view with a fixed header and footer section and a scrollable data section in the middle. This widget supports paging and columns.

2.1. Columns

The Column class defines the Cell used to render a column. Implement Column.getValue(Object) to retrieve the field value from the row object that will be rendered in the Cell.

2.2. Headers and Footers

A Header can be placed at the top (header) or bottom (footer) of the DataGrid. You can specify a header as text using AbstractCellTable.addColumn(Column, String), or you can create a custom Header that can change with the value of the cells, such as a column total. The Header will be rendered every time the row data changes or the table is redrawn. If you pass the same header instance (==) into adjacent columns, the header will span the columns.

3. Creating new Web Application Project

First we will create a new web application project. To do that go to File -> New -> Other and type ‘Web Application Project’ in the Wizards: Text box. (See below)

Figure 1. Create new Web Application Project
Figure 1. Create new Web Application Project

Select and click next. Give the project name and package name. Select the location of the project. You can choose to create it in the workspace (default) value or give your own path. Let the other values as default. In the end you can choose whether you want to generate the sample code. For our example we will select it.

Figure 2. Project Setup
Figure 2. Project Setup

Click Finish. GWT plugin will generate some sample classes and files.

4. Important classes

Below are the list of files which we are interested in. We can remove ‘server’ and ‘shared’ packages and it’s classes.

4.1. GWTDataGrid.gwt.xml

This is the GWT configuration class.

GWTDataGrid.gwt.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit 2.6.0//EN"
"http://google-web-toolkit.googlecode.com/svn/tags/2.6.0/distro-source/core/src/gwt-module.dtd">
<module rename-to='gwtdatagrid'>
  <inherits name='com.google.gwt.user.User'/>
  <inherits name='com.google.gwt.user.theme.clean.Clean'/>
  <entry-point class='com.javacodegeeks.client.GWTDataGrid'/>

  <source path='client'/>

  <add-linker name="xsiframe"/>
</module>

When updating your version of GWT, you should also update this DTD reference, so that your app can take advantage of the latest GWT module capabilities.

<inherits name='com.google.gwt.user.User'/> inherits the core Web Toolkit stuff.
<entry-point class='com.javacodegeeks.client.GWTDataGrid'/> specifies the application entry point class.
<source path='client'/> specifies the paths for translatable code.

4.2. GWTDataGrid.java

This is the entry point class.

GWTDataGrid.java

package com.javacodegeeks.client;

import java.util.Arrays;
import java.util.List;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.cellview.client.DataGrid;
import com.google.gwt.user.cellview.client.HasKeyboardSelectionPolicy.KeyboardSelectionPolicy;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.RootLayoutPanel;
import com.google.gwt.user.client.ui.SimpleLayoutPanel;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SingleSelectionModel;

/**
* Entry point class define <code>onModuleLoad()</code>.
*/
public class GWTDataGrid implements EntryPoint {
/**
* A simple data type that represents an Address.
*/
private static class Address {
private final String houseNumber;
private final String streetName;
private final String county;
private final String postCode;
private final String country;

public Address(String houseNumber, String streetName, String county, String postCode, String country) {
  this.houseNumber = houseNumber;
  this.streetName = streetName;
  this.county = county;
  this.postCode = postCode;
  this.country = country;
 }
}

/*
* The list of data to display.
*/
private static final List<Address> ADDRESS = Arrays.asList(
  new Address("123", "Lloyds Road", "Middlesex", "TE0 6NB", "United Kingdom")
  ,new Address("456", "Oxford Street", "Oxford", "LK9 0CV", "United Kingdom"));

public void onModuleLoad() {
  DataGrid<Address> table = new DataGrid<Address>();
  table.setKeyboardSelectionPolicy(KeyboardSelectionPolicy.ENABLED);

  TextColumn<Address> houseNumber = new TextColumn<Address>() {
    @Override
    public String getValue(Address object) {
    return object.houseNumber;
  }};
  table.addColumn(houseNumber, "House Number");

  TextColumn<Address> streetName = new TextColumn<Address>() {
    @Override
    public String getValue(Address object) {
    return object.streetName;
  }};
 table.addColumn(streetName, "Street Name");

  TextColumn<Address> county = new TextColumn<Address>() {
    @Override
    public String getValue(Address object) {
    return object.county;
  }};
 table.addColumn(county, "County");

  TextColumn<Address> postCode = new TextColumn<Address>() {
    @Override
    public String getValue(Address object) {
    return object.postCode;
  }};
  table.addColumn(postCode, "Post Code");

  TextColumn<Address> country = new TextColumn<Address>() {
    @Override
    public String getValue(Address object) {
    return object.country;
  }};
  table.addColumn(country, "Country");

// Add a selection model to handle user selection.
  final SingleSelectionModel<Address> selectionModel = new SingleSelectionModel<Address>();
  table.setSelectionModel(selectionModel);
  selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
    public void onSelectionChange(SelectionChangeEvent event) {
    Address selected = selectionModel.getSelectedObject();
    if (selected != null) {
      Window.alert("You selected: " + selected.houseNumber + " " + selected.streetName + " " + selected.county
+ " " + selected.postCode + " " + selected.country);
}
}
});
  table.setRowCount(ADDRESS.size(), true);
  table.setRowData(0, ADDRESS);
  table.setWidth("100%");
  SimpleLayoutPanel slp = new SimpleLayoutPanel();
  slp.add(table);

// Add it to the root panel.
RootLayoutPanel.get().add(slp);
}
}

5. Compile

To compile the application right click on the project -> Google -> GWT Compile

Figure 3. GWT Compile
Figure 3. GWT Compile

When you click on ‘GWT Compile‘ the below window is displayed.

Figure 4. GWT Compile 2
Figure 4. GWT Compile 2

Click on the ‘Compile’ button. In the Console you will see the below logs

Compiling module com.javacodegeeks.GWTDataGrid
  Compiling 5 permutations
    Compiling permutation 0...
    Compiling permutation 1...
    Compiling permutation 2...
    Compiling permutation 3...
    Compiling permutation 4...
  Compile of permutations succeeded
Linking into E:\meraj\study\eclipse-workspace\GWTDataGrid\war\gwtdatagrid
Link succeeded
Compilation succeeded -- 29.555s

6. Running the application

To run the application right click on the project, go to ‘Run As’ and click Web Application (GWT Classic Dev Mode)

Figure 5. Run Application
Figure 5. Run Application

You will see the below logs in the Console.

Initializing App Engine server
May 15, 2015 11:22:15 PM com.google.apphosting.utils.config.AppEngineWebXmlReader readAppEngineWebXml
INFO: Successfully processed E:\meraj\study\eclipse-workspace\GWTDataGrid\war\WEB-INF/appengine-web.xml
May 15, 2015 11:22:15 PM com.google.apphosting.utils.config.AbstractConfigXmlReader readConfigXml
INFO: Successfully processed E:\meraj\study\eclipse-workspace\GWTDataGrid\war\WEB-INF/web.xml
May 15, 2015 11:22:16 PM com.google.appengine.tools.development.SystemPropertiesManager setSystemProperties
INFO: Overwriting system property key 'java.util.logging.config.file', value 'E:\meraj\study\eclipse\plugins\com.google.appengine.eclipse.sdkbundle_1.9.19\appengine-java-sdk-1.9.19\config\sdk\logging.properties' with value 'WEB-INF/logging.properties' from 'E:\meraj\study\eclipse-workspace\GWTDataGrid\war\WEB-INF\appengine-web.xml'
May 15, 2015 11:22:16 PM com.google.apphosting.utils.jetty.JettyLogger info
INFO: Logging to JettyLogger(null) via com.google.apphosting.utils.jetty.JettyLogger
May 15, 2015 11:22:16 PM com.google.appengine.tools.development.DevAppServerImpl setServerTimeZone
WARNING: Unable to set the TimeZone to UTC (this is expected if running on JDK 8)
May 15, 2015 11:22:17 PM com.google.apphosting.utils.jetty.JettyLogger info
INFO: jetty-6.1.x
May 15, 2015 11:22:21 PM com.google.apphosting.utils.jetty.JettyLogger info
INFO: Started SelectChannelConnector@0.0.0.0:8888
May 15, 2015 11:22:21 PM com.google.appengine.tools.development.AbstractModule startup
INFO: Module instance default is running at http://localhost:8888/
May 15, 2015 11:22:21 PM com.google.appengine.tools.development.AbstractModule startup
INFO: The admin console is running at http://localhost:8888/_ah/admin
May 15, 2015 11:22:21 PM com.google.appengine.tools.development.DevAppServerImpl doStart
INFO: Dev App Server is now running

In the Development Mode tab you will see a URL – http://127.0.0.1:8888/GWTDataGrid.html?gwt.codesvr=127.0.0.1:9997 Copy the URL and paste in the Internet Explorer, remove the part after ‘.html’. So the URL becomes – http://127.0.0.1:8888/GWTDataGrid.html. Press Enter. You will see the below window.

Figure 6. Output
Figure 6. Output

7. DataGrid vs CellTable

People normally get confused between DataGrid and CellTable. Below are the list of some of the differences between them which can help to decide which one should be used.

  1. DataGrid provides RequiresResize.onResize() functionality while CellTable doesn’t.
  2. DataGrid headers are fixed and do not move while scrolling the content

8. Download the source file

This was an example of GWT DataGrid

Download
You can download the full source code of this example here: GWTDataGrid

Mohammad Meraj Zia

Senior Java Developer
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button