Over a million developers have joined DZone.
Refcard #001

GWT Style, Configuration and JSNI Reference

Using the Google Web Toolkit

Written by

Robert Hansen Sr. Software Eng., CuriousBob

Introduces Ajax, a group interrelated techniques used in client-side web development for creating asynchronous web applications.

Free PDF
Section 1

About Google Web Toolkit (GWT)

The Google Web Toolkit is a set of tools for writing JavaScript applications in Java. The cornerstone of the tool suite is a Java to JavaScript compiler that can not only compile Java down to JavaScript, but can also compress and optimize your code as well. GWT was released to the public in June of 2006 and has been an overwhelming success, boasting 1 million downloads in its first year.

The benefit of using GWT over some of the other JavaScript frameworks like JQuery or Ext-JS is the environment in which you code. GWT allows a Java developer to use the same tools they use today like Eclipse, Maven, and JUnit, making the transition from Java server-side development to GWT client-side development nearly seamless.

The GWT toolkit comes ready with its own widget library, internationalization tools, image bundling tools, tools for client-server communication, and many others. Since its launch GWT has become an open-source project, and although led by the GWT team at Google, many from the community have contributed patches to the toolkit. GWT boasts a thriving community, proving for a multitude of free widgets, integration tools, and utilities.

This reference card is a guide to everything that your IDE can't already tell you. Specifically, IDEs like Eclipse provide auto-completion capabilities for perusing a list of methods on an object, and often they also provide support for viewing javadocs in the IDE as well. This refcard is meant to supplement that capability by providing details that are only available in books and online documentation. Specifically this includes a CSS style for the widgets that ship with GWT, a reference for the JavaScript Native Interface, and a complete guide to the GWT module configuration file.

Section 3

Styling Widgets with CSS

Styling widgets is done using Cascading Style Sheets (CSS). CSS can be applied to the widgets in the application three different ways.

Adding a style element inside the <head> of the HTML page that is hosting the application.

<style type='text/css'>
/* CSS style rules*/

Adding a <link> element to the <head> of the HTML page, referencing an external CSS stylesheet.

<link type="text/css' rel='stylesheet' href='url-to-file.css' />

Adding a <stylesheet> element to the GWT project's module configuration, causing the stylesheet to be injected into the host HTML page.

<stylesheet src='url-to-file.css'/>

Most of the widgets that come with GWT have been pre-assigned CSS class names. For example, the Button widget uses the CSS class name gwt-Button. So you could set the width of all Button widgets in your application by using the following CSS rule. In order to reference a CSS class in a CSS rule you prefix the class name with a period ".".

.gwt-Button {
        width: 100px;

Altering Style Names

You can programmatically alter the CSS class name used on a widget by calling any of these methods.


In HTML you may provide any number of CSS class names on an element by separating them with spaces, like in the HTML snippet below.

<div class="style1 style2 style3"></div>

The primary style name in GWT is defined as the first style name in the class attribute. In the example provided, this would be the style "style1". Calling setStylePrimaryName() allows you to alter this first style.


When you add a dependent style name, its name in the HTML is the primary name plus the depende nt name, separated with a dash ("-").


Button button = new Button();


<BUTTON class="foo foo-bar"></BUTTON>


Using setStylename() will clear all current style names, including the primary style name, and adds the one provided.


Adds an additional style name to any existing style names.


Button button = new Button();


<BUTTON class="foo bar"></BUTTON>


Allows you to remove an existing style name on a widget.

Default GWT Widget Style Names

Most of the widgets provided by the GWT library have pre-defined primary style names. The following is a list of the default names for each widget.

Widget Default Name
.gwt-Button { }
.gwt-CheckBox { }
.gwt-DialogBox { the box
container }
.gwt-DialogBox .Caption { the box caption }
.gwt-DisclosurePanel { primary
style }
.gwt-DisclosurePanel-open { when open }
.gwt-DisclosurePanel-closed { when closed }
.header { the panel header area }
.content { the panel content area }
.gwt-HorizontalSplitPanel { the
panel }
.gwt-HorizontalSplitPanel hsplitter { splitter }
.gwt-HTML { }
.gwt-Hyperlink { }
.gwt-Image { }

Note: Transformations between clipped and upclipped will result in the loss of any CSS style names that were set or added.

.gwt-Label { }
.gwt-ListBox { }
.gwt-MenuBar { the menu bar
itself }
.gwt-MenuBar .gwt-MenuItem { menu items }
.gwt-MenuBar .gwt-MenuItem-selected { selected menu items
.gwt-PasswordTextBox { primary
style }
.gwt-PasswordTextBox-readonly { dependent style set when the
password text box is read-only }
.gwt-PushButton-up {}
.gwt-PushButton-down {}
.gwt-PushButton-up-hovering {}
.gwt-PushButton-down-hovering {}
.gwt-PushButton-up-disabled {}
.gwt-PushButton-down-disabled {}
<any of the above> .html-face {}
.gwt-RadioButton { }
.gwt-RichTextArea {
.gwt-StackPanel { the panel
itself }
.gwt-StackPanel .gwt-StackPanelItem { unselected items }
.gwt-StackPanel .gwt-StackPanelItem-selected { selected items
.gwt-SuggestBox { the suggest
box itself }
.gwt-SuggestBoxPopup { the suggestion popup }
.gwt-SuggestBoxPopup .item { an unselected suggestion }
.gwt-SuggestBoxPopup .item-selected { a selected suggestion
.gwt-TabBar { the tab bar itself
.gwt-TabBar .gwt-TabBarFirst { the left edge of the bar }
.gwt-TabBar .gwt-TabBarRest { the right edge of the bar }
.gwt-TabBar .gwt-TabBarItem { unselected tabs }
.gwt-TabBar .gwt-TabBarItem-selected { additional style for
selected tabs }
.gwt-TabPanel { the tab panel
itself }
.gwt-TabPanelBottom { the bottom section of the tab panel (the deck
containing the widget) }
.gwt-TextArea { primary style
.gwt-TextArea-readonly { dependent style set when the text area is
read-only }
.gwt-TextBox { primary style
.gwt-TextBox-readonly { dependent style set when the text box is
read-only }
.gwt- ToggleButton-up {}
.gwt- ToggleButton-down {}
.gwt- ToggleButton-up-hovering {}
.gwt- ToggleButton-down-hovering {}
.gwt- ToggleButton-up-disabled {}
gwt- ToggleButton-down-disabled {}
<any of the above> .html-face {}
.gwt-Tree { the tree itself
.gwt-Tree .gwt-TreeItem { a tree item }
.gwt-Tree .gwt-TreeItem-selected { a selected tree item
.gwt-VerticalSplitPanel { the
panel itself }
.gwt-VerticalSplitPanel vsplitter { the splitter }
Section 4

GWT Model Configuration

A module in GWT is best described as a set of classes that are bound by a single module configuration file. The module configuration defines what classes are a part of the module, what other modules that the module depends on, as well as rules for deferred binding, resource injection, and everything else that the GWT compiler and shell needs to know about your module.

A module configuration file is located in the GWT project, with an extension of ".gwt.xml". The location on the classpath and the module configuration file name determine the full module name.

Module Name = Java Package + Module File Name (-gwt.xml)

For example, if you have a module configuration file named Demo.gwt.xml, in the java package com.gwtsandbox.demo, the module name would be com.gwtsandbox.demo.Demo.

Hot Tip

The module configuration is only used at design and compile-time, it is not used at run-time. This is a common mistake for new GWT developers.

Simple Module Configuration

A simple module configuration must inherit the User module and specify a single entry point. The entry point is the class that implements the EntryPoint interface and acts as the starting point for the application.

        <inherits name='com.google.gwt.user.User' />
        <entry-point class=’org.gwtsandbox.demo.client.Demo’ />

From the basic module configuration you can build on it by adding additional elements to inherit additional modules, change the default source path, add servlet mappings, and add deferred binding rules.

Inheriting Modules

If your GWT project needs to reference external GWT modules you must explicitly inherit them in your module configuration. The core GWT libraries are split into several modules, each of which is listed here. You will always need to include the User module, and optionally one or more of the others.

GWT widgets and core utilities

<inherits name="com.google.gwt.user.User"

RequestBuilder and associated classes

<inherits name="com.google.gwt.http.HTTP"

Internationalization tools and date/number formatting

<inherits name="com.google.gwt.i18n.I18N"

Tools for using RPC with JavaScript Object Notation

<inherits name="com.google.gwt.json.JSON"

XML parser and associated classes

<inherits name="com.google.gwt.xml.XML"

Source Path

The source path is a relative path name used to override the default location of the client-side Java source destined to be compiled into JavaScript. The source path you specify is appended to the path where the module configuration file resides, and you may specify multiple source paths.

<source path="path"/>

By default the source path is "client". So by way of example, if your GWT module configuration file is located at com.example.MyApp.gwt.xml, then the default path of "client" will dictate that your client-side Java source will be located in the Java package com.example.client.*, as well as all packages below this one.

All source code in the source path(s) must be able to be compiled to JavaScript with the GWT compiler. This implies that only classes from the JRE emulation library and GWT user library be used. For example, you can not include Java servlets or use the java.sql.* classes under this path.

Public Path

The public path is used to store non-Java files that need to be included in the application. This includes HTML files, JavaScript files, images, CSS, and anything else. By default this will be the "public" directory below where the module configuration is stored.

You can override the default by using the <public> tag in the module configuration.

<public path="path"/>

You may specify multiple public paths if required for your project.

Defining GWT-RPC Servlets

You can use the <servlet> tag in the module configuration to define your GWT-RPC servlets.

<servlet path="/path" class="org.gwtsandbox.demo.server.Demo" />

The path specified should be absolute.

Hot Tip

These servlet mappings are for the benefit of hosted-mode use only, and does not imply that these mappings will be carried over to your production environment. For that you would set them up in the deployment descriptor, just as you would with any other servlet.

Resource Injection

You can have external JavaScript and CSS files automatically injected into the hosting web page. By injecting the resources you avoid the need to have the hosting HTML page explicitly include them with %lt;link> and <script> tags. Resources loaded in this way will be loaded prior to the executing of the GWT application.

<script src="js-url"/>
<stylesheet src="css-url"/>

To inject a resource you can either place the JavaScript or CSS file into the public package of the GWT module (see above), referencing it with a relative path, or reference an external CSS file by using a full URL.

Deferred Binding

In some cases you need to write low-level functionality that differs based on the client browser, or you need to trigger a generator to generate code at compile time. For these functions you use deferred binding. Deferred binding allows you to write code to an interface and have the concrete class determined at compile-time.

For example, you may be familiar with GWT's RPC mechanism. You use the GWT.create() method to return a concrete class that can serialize and send your data to the server.

MyServiceAsync svc = (MyServiceAsync) GWT.create(MyService.class);

When this code is compiled the compiler examines the argument passed to the create method, then attempts to match the target class to a set of rules that reside in the module configuration.

Using Generate-With to Trigger Generators

In this case the compiler rule is specified in the module com.google.gwt.user.RemoteService, which is inherited from your module when using GWT-RPC.

<generate-with class="com.google.gwt.user.rebind.rpc.ServiceInterfaceProxyGenerator">
        <when-type-assignable class="com.google.gwt.user.client.rpc.RemoteService"/>

This rule states that when the target class of the GWT.create() is assignable to RemoteService, that the generator ServiceInterfaceProxyGenerator is executed. The generator then creates the code and returns the name of the class that should be returned by the create method.

Using Replace-With to Trigger Class Replacement

The other use of deferred binding is to specify a alternate class to be returned by GWT.create() based on available properties. The most common use of this is to use an alternate class depending on the client browser. The property that can be examined to determine this is "user.agent".

For example, the DOM class in GWT is used to perform low-level functions, where the browser implementations can differ. In order to allow for different browsers the following rule can be found in the com.google.gwt.user.DOM module.

<replace-with class="com.google.gwt.user.client.impl.DOMImplIE6">
        <when-type-is class="com.google.gwt.user.client.impl.DOMImpl"/>
        <when-property-is name="user.agent" value="ie6"/>

In the DOM class the following code is used to "create" the correct implementation of the DOM class.

DOMImpl impl = (DOMImpl) GWT.create(DOMImpl.class);

When the user.agent property is "ie6" the replace-with rule specified above will return a DOM implementation that is specifically designed for Internet Explorer.

Generate-With and Replace-With Expressions

The following expression tags can be used within generate-with and replace-with tags. When any of the expression tags within the rule returns a true value, the code generation or class replacement is performed.

<when-property-is name="prop-name" value="matched-value" />

Returns true when the value of the property matches the specified value. For details on setting properties, see the Setting Properties section.

<when-type-assignable class="assignable-type" />

The target class is tested to see if it can be assigned to the specified assignable type.

<when-type-is class="type" />

Similar to when-type-assignable, except that the class must be an exact match.

<all>, <any>, <none>

Use these expression tags to group other expression tags. The <all> tag implies that all of the tags contained within it must be true. The <any> tag requires only one of the containing expressions to be true. The <none> tag requires that all contained expression tags return false.

Setting Properties

Property names and their possible values can be defined in the module configuration.

<define-property name="prop-name" values="vals" />

Creates a new property and comma separated list of the possible values. For example, you could use the following to define a view property that could be used to define three unique view types for the application.

<extend-property name="prop-name" values="vals" />

Extends the possible values for a property that has already been defined.

<set-property name="prop-name" value="value" />

Sets the value of a defined property. The value must be one of the possible values as defined by the <define-property> tag or one of the extended values as defined by the <extended-property> tag.

<property-provider name="prop-name">

Property values can be set at run-time by supplying a property provider. The contents of the <property-provider> tag is a block of JavaScript that returns the property value. The JavaScript code must be placed in a CDATA block to avoid parsing errors.

<property-provider name="view"><![CDATA[
        var view = __gwt_getMetaProperty("view");
        if (!__gwt_isKnownPropertyValue("view", view)) {
                view = 'basic';
        return view;

The JavaScript block can utilize the __gwt_getMetaProperty() method to get the value of GWT property defined in a <meta> tag in the HTML page, and can use __gwt_isKnownPropertyValue() to test that it is an allowed value. Here's an example of using the HTML <meta> tag to set the view as "extended".

<meta name="gwt:property" content="view=extended" />

Section 5

JavaScript Native Interface

The JSNI interface is used as a gateway between your Java and JavaScript code. It allows you to create Java methods that have JavaScript code in the body, and then to have the JavaScript code call Java methods.

JSNI Methods

Methods containing JavaScript must use the native modifier so that a Java compiler will not validate its contents. Methods in Java marked as native may not have a method body.

public native void doStuff ();

GWT introduces a special comment syntax that follows the Java native rule of having no method body, while allowing you to provide JavaScript code that can be picked up by the GWT compiler.

public native void doStuff () /*-{
        // JavaScript code goes here

JSNI Variables

Due to the way GWT applications load, the "window" and "document" JavaScript objects point to the wrong objects. GWT provides these special variables for use in JSNI methods.

Variable Purpose
$wnd Alias for the JavaScript "window" object
$doc Alias for the JavaScript "document" object

public native void doStuff () /*-{
        $wnd.alert("Hello World");

Passing Values Between Java and JavaScript

You can pass both Java primitives and objects into a JSNI method. The following rules define how Java values are available in JSNI methods and visa versa.

Java type Where created JavaScript type
numeric primitive (byte, short, char, int, long, float, double) Both numeric value
boolean primitive Both boolean value
String Both string value
JavaScriptObject Must be created in JSNI method An object
Java array Must be created in Java Not directly usable, can be passed back into Java code
All other Java objects Must be created in Java Special, see below

JSNI methods that have Java objects passed to them may use a special syntax in order to call methods and access properties of the object.

Calling Java Methods from JavaScript

The following syntax is used to call a Java method from a JSNI method.

[instance-expr.]@class-name::method-name(param-signature) (arguments)

The instance expression is the name of the variable passed into the method, or "this" to refer to the class instance, or blank for calling static methods.

The class name is the fully qualified name, followed by double colons and the method name.

The parameter signature is a list of the parameter types in the method that you are calling. This is needed in order to distinguish between two Java methods that have the same name but different sets or parameters. The following table defines the codes used to specify the parameter type.

Type Code Java Type
Z Boolean
B Byte
C Char
S Short
I Int
J Long
F Float
D Double
L fully-qualified-class ; Java objects. Uses "/" to delimit parts of the package name, e.g. "Ljava/lang/String;"
[ type Int

Types are listed one after the other without spaces. For example, "ZLjava/lang/String;[F" defines the method signature (boolean, String, float[]).

The argument list is exactly that, a list of the arguments being passed to the method. Below are examples of calling methods from JavaScript on well known Java types.

Calling instance method with no arguments:

public native long extractTime (Date date) /*-{
        return date.@java.util.Date::getTime()();

Calling instance method with a single argument:

public native void appendText (StringBuffer sb, String txt)

Calling static method with multiple arguments:

public native int maxValue (int x, int y) /*-{
        return @java.lang.Math::max(II)(x, y);

Accessing Java properties from JavaScript

Accessing properties of a Java object from JavaScript is similar to calling a Java method.


The same value rules apply as calling methods (see Calling Java Methods from JavaScript). The instance expression is the variable name passed into the JSNI method, "this" for the instance of the class, or left off to access a static property. The class name is the fully qualified package and class, and is separated from the field name with two colons. On the following page are some examples.

Reading and writing to field on "this"

// int currentIndex;
var cur = this.@org.example.Demo::currentIndex;
this.@org.example.Demo::currentIndex = 0;

Reading and writing to field on object

// String welcomeMessage;
var msg = obj.@org.example.Demo::welcomeMessage;
obj.@org.example.Demo::welcomeMessage = "Hello";

Reading and writing to a static field

// boolean lastResult;
var last = @org.example.Demo::lastResult;
@org.example.Demo::lastResult = true;

Hot Tip

You can use JSNI to dynamically create JavaScript methods that can be used by external JavaScript code to make calls into your application. The following code creates a JavaScript method jsMethod(string) on startup in the browser that can be used to call the javaMethod(String) in the GWT application.

public void onModuleLoad () {
private native void createJsMethod (Main obj) /*-{
        $wnd.jsMethod = function (s) {
public String javaMethod (String in) {
        return "I got your message: " + in;
<button onclick="alert(jsMethod('Hello'))">Say Hello</button>


  • Featured
  • Latest
  • Popular
Getting Started With Docker
Teaches you typical Docker workflows, building images, creating Dockerfiles, and includes helpful commands to easily automate infrastructure and contain your distributed application.
10.3k 7,449
Getting Started With Real User Monitoring
Teaches you how to use new web standards—like W3C’s Beacon API—to see how your site is performing for actual users, letting you better understand how to improve overall user experience.
4,492 3,749
Core Java
Gives you an overview of key aspects of the Java language and references on the core library, commonly used tools, and new Java 8 features.
104.2k 264.3k
JavaFX 8
Gives you what you need to start using the powerful JavaFX 8 UI and graphics tool with code snippets and visual examples of shapes and controls.
6,829 9,071
Continuous Delivery With Jenkins Workflow
Provides an introduction to the Jenkins Workflow plugin, a tool that extends the popular CD application to manage even the most complex software pipelines and help you continuously deliver more efficiently.
8,722 9,902
Functional Programming in JavaScript
Explains functions, data types, and techniques to demonstrate the functional paradigm through the familiar JavaScript language.
12k 8,797
Java Caching
Explores the building blocks of JCache and other caching APIs, as well as multiple strategies for implementing temporary data storage in your application.
10.5k 10.7k
Getting Started With Microservices
Still re-deploying your entire application for one small update? Microservices deploy modular updates and increase the speed of application deployments.
13.8k 14.3k
Getting Started With MQTT
Explores the fundamentals of MQTT, including message types, QoS levels, and security.
6,098 7,234
Monitoring NGINX
Overcome dropped connections, server errors, and more by efficiently monitoring your NGINX web server.
4,889 3,862
Getting Started With Apache Tomcat
Learn Apache Tomcat, a pure Java open-source web server that implements the Java Servlet, JavaServer Pages, and Expression Language specifications.
8,896 7,380
IntelliJ IDEA Essentials
Helps Java developers navigate the various facets of this world-class IDE, with tips, tricks, shortcuts, and quick tutorials on editor basics, navigation, and more.
20.4k 91.1k
{{ card.title }}
{{card.downloads | formatCount }} {{card.views | formatCount }}

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}