GWT Tutorial
GWT Tutorial
GWT Tutorial
GWT is an open source, completely free, and used by thousands of developers around
the world. It is licensed under the Apache License version 2.0.
This tutorial will give you a great understanding of GWT concepts needed to get a web
application up and running.
Audience
This tutorial is designed for software professionals who are willing to learn GWT
programming in simple and easy steps. This will also give you great understanding on
GWT Programming concepts.
After completing this tutorial, you will be at intermediate level of expertise from where
you can take yourself at higher level of expertise.
Prerequisites
Before proceeding with this tutorial, you should have a basic understanding of Java
programming language, text editor, and execution of programs, etc. Because we are
going to develop web-based applications using GWT, it will be good if you have an
understanding of other web technologies such as HTML, CSS, and AJAX.
All the content and graphics published in this e-book are the property of Tutorials Point
(I) Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or
republish any contents or a part of contents of this e-book in any manner without written
consent of the publisher.
We strive to update the contents of our website and tutorials as timely and as precisely
as possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I)
Pvt. Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of
our website or its contents including this tutorial. If you discover any errors on our
website or in this tutorial, please notify us at [email protected]
i
GWT
Table of Contents
About the Tutorial ................................................................................................................................. i
Audience ............................................................................................................................................... i
Prerequisites ......................................................................................................................................... i
ii
GWT
Step 3 - Modify Style Sheet: HelloWorld.css ........................................................................................17
iii
GWT
Button Widget Example ......................................................................................................................79
iv
GWT
GWT - CellTable Widget ....................................................................................................................233
v
GWT
Introduction ......................................................................................................................................412
Bookmarking Example.......................................................................................................................480
vii
1. GWT – OVERVIEW GWT
What is GWT?
Google Web Toolkit (GWT) is a development toolkit to create RICH Internet Applications
(RIA). Here are some of its notable features:
GWT is an open source, completely free, and used by thousands of developers around
the world. It is licensed under the Apache License version 2.0.
Again being Java based, GWT has a low learning curve for Java Developers.
GWT generates optimized JavaScript code, produces browser's specific JavaScript code
by self.
GWT provides widgets library which provides most of the tasks required in an
application.
GWT is extensible and custom widget based which can be created to cater to various
application needs.
On top of everything, GWT applications can run on all major browsers and smart phones
including Android and iOS based phones/tablets.
8
GWT
Disadvantages of GWT
Although GWT offers plenty of advantages, it suffers from the following disadvantages
Not Indexable: Web pages generated by GWT would not be indexed by search
engines because these applications are generated dynamically.
Not Degradable: If your application user disables JavaScript then user will just see
the basic page and nothing more.
Not Designer's Friendly: GWT is not suitable for web designers who prefer using
plain HTML with placeholders for inserting dynamic content at a later point in time.
GWT Java to JavaScript compiler: This is the most important part of GWT which
makes it a powerful tool for building RIAs. The GWT compiler is used to translate all
the application code written in Java into JavaScript.
JRE Emulation library: Google Web Toolkit includes a library that emulates a subset
of the Java runtime library. The list includes java.lang, java.lang.annotation,
java.math, java.io, java.sql, java.util and java.util.logging
GWT UI building library: This part of GWT consists of many subparts which includes
the actual UI components, RPC support, History management, and much more.
GWT also provides a GWT Hosted Web Browser which lets you run and execute your GWT
applications in hosted mode, where your code runs as Java in the Java Virtual Machine without
compiling to JavaScript.
9
2. GWT ENVIRONMENT GWT
This tutorial will guide you on how to prepare a development environment to start your work
with GWT Framework. This tutorial will also teach you how to setup JDK, Tomcat and Eclipse
on your machine before you setup GWT Framework:
System Requirement
GWT requires JDK 1.6 or higher so the very first requirement is to have JDK installed in your
machine.
Follow the given steps to setup your environment to start with GWT application development.
OS Task Command
10
GWT
OS Generated Output
Set the JAVA_HOME environment variable to point to the base directory location where Java
is installed on your machine. For example
OS Output
11
GWT
OS Output
Windows Append the string; %JAVA_HOME%\bin to the end of the system variable,
Path.
Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder,
Eclipse, IntelliJ IDEA, or Sun ONE Studio, compile and run a simple program to confirm that
the IDE knows where you installed Java, otherwise do proper setup as given document of the
IDE.
Eclipse can be started by executing the following commands on windows machine, or you can
simply double click on eclipse.exe
%C:\eclipse\eclipse.exe
Eclipse can be started by executing the following commands on UNIX (Solaris, Linux, etc.)
machine:
$/usr/local/eclipse/eclipse
After a successful startup, if everything is fine then it should display following result:
12
GWT
After a successful setup for the GWT plugin, if everything is fine, then it should display the
following screen which has Google icon marked in red rectangle as shown below:
13
GWT
Tomcat can be started by executing the following commands on windows machine, or you can
simply double click on startup.bat
%CATALINA_HOME%\bin\startup.bat
or /usr/local/apache-tomcat-6.0.33/bin/startup.sh
After a successful startup, the default web applications included with Tomcat will be available
by visiting http://localhost:8080/. If everything is fine then it should display following
result:
14
GWT
Further information about configuring and running Tomcat can be found in the documentation
included here, as well as on the Tomcat web site: http://tomcat.apache.org
%CATALINA_HOME%\bin\shutdown
Or C:\apache-tomcat-5.5.29\bin\shutdown
Tomcat can be stopped by executing the following commands on UNIX (Solaris, Linux, etc.)
machine:
$CATALINA_HOME/bin/shutdown.sh
Or
/usr/local/apache-tomcat-5.5.29/bin/shutdown.sh
15
3. GWT APPLICATIONS GWT
Before we start with creating actual “HelloWorld” application using GWT, let us see what the
actual parts of a GWT application are:
A GWT application consists of following four important parts out of which last part is optional
but first three parts are mandatory
Module descriptors
Public resources
Client-side code
Server-side code
Sample locations of different parts of a typical GWT Hello World application looks like the
below:
Name Location
Module Descriptors
A module descriptor is the configuration file in the form of XML which is used to configure a
GWT application.
A module descriptor file extension is *.gwt.xml, where * is the name of the application and
this file should reside in the project's root.
<!-- specify the paths for static files like html, css etc. -->
<public path='...'/>
<public path='...'/>
<!-- specify the paths for external style sheet files -->
<stylesheet src="css-url" />
<stylesheet src="css-url" />
</module>
1 <module rename-to="helloworld">
17
GWT
4 <source path="path" />This specifies the names of source folders which GWT
compiler will search for source compilation.
5 <public path="path" />The public path is the place in your project where static
resources referenced by your GWT module, such as CSS or images, are stored.
The default public path is the public subdirectory underneath where the Module
XML File is stored.
Public Resources
These are the various files referenced by your GWT module, such as Host HTML page, CSS or
images.
The location of these resources can be configured using <public path="path" /> element in
module configuration file. By default, it is the public subdirectory underneath where the
Module XML File is stored.
When you compile your application into JavaScript, all the files that can be found on your
public path are copied to the module's output directory.
The most important public resource is host page which is used to invoke actual GWT
application. A typical HTML host page for an application might not include any visible HTML
body content at all but it is always expected to include GWT application via a <script.../> tag
as follows
<html>
<head>
<title>Hello World</title>
<link rel="stylesheet" href="HelloWorld.css"/>
18
GWT
<h1>Hello World</h1>
<p>Welcome to first GWT application</p>
</body>
</html>
Following is the sample style sheet which we have included in our host page:
body {
text-align: center;
font-family: verdana, sans-serif;
}
h1 {
font-size: 2em;
font-weight: bold;
color: #777777;
margin: 40px 0px 70px;
text-align: center;
}
Client-side Code
This is the actual Java code written for implementing the business logic of the application and
with this, GWT compiler translates into JavaScript, which will eventually run inside the
browser. The location of these resources can be configured using <source path="path" />
element in module configuration file.
For example, Entry Point code will be used as client-side code and its location will be specified
using <source path="path" />.
19
GWT
A module entry-point is any class that is assignable to EntryPoint and that can be
constructed without parameters. When a module is loaded, every entry point class is
instantiated and its EntryPoint.onModuleLoad() method gets called. A sample HelloWorld
Entry Point class will be as follows:
Server-side Code
This is the server side part of your application and it is very much optional. If you are not
doing any backend processing within your application, then you do not need this part.
However, if there is some processing required at backend and your client-side application
interacts with the server, then you will have to develop these components.
The next chapter will make use of all the above-mentioned concepts to create a HelloWorld
application using Eclipse IDE.
20
4. GWT – CREATE APPLICATION GWT
As the power of GWT lies in Write in Java, Run in JavaScript, we'll be using Java IDE
Eclipse to demonstrate our examples.
21
GWT
Unselect Use Google App Engine because we're not using it in this project and leave other
default values (keep the Generate Sample project code option checked as such and click
Finish Button).
Once your project is created successfully, you will have the following content in your Project
Explorer:
Folder Location
Client folder containing the client-side specific java classes responsible for
client UI display.
Server folder containing the server-side java classes responsible for server
src
side processing.
22
GWT
Shared folder containing the java model class to transfer data from server to
client and vice versa.
test Client folder containing the java classes responsible to test gwt client side
code.
This is the most important part, it represents the actual deployable web
application.
war
WEB-INF containing compiled classes, gwt libraries, servlet libraries.
<!-- Inherit the default GWT style sheet. You can change -->
<!-- the theme of your GWT application by uncommenting -->
<!-- any one of the following lines. -->
<inherits name='com.google.gwt.user.theme.clean.Clean'/>
<!-- <inherits name='com.google.gwt.user.theme.chrome.Chrome'/> -->
<!-- <inherits name='com.google.gwt.user.theme.dark.Dark'/> -->
23
GWT
</module>
body {
text-align: center;
font-family: verdana, sans-serif;
}
h1 {
font-size: 2em;
font-weight: bold;
color: #777777;
margin: 40px 0px 70px;
text-align: center;
}
<html>
<head>
24
GWT
<title>Hello World</title>
<link rel="stylesheet" href="HelloWorld.css"/>
<script language="javascript" src="helloworld/helloworld.nocache.js">
</script>
</head>
<body>
<h1>Hello World</h1>
<p>Welcome to first GWT application</p>
</body>
</html>
You can create more static files like HTML, CSS or images in the same source directory or you
can create further sub-directories and move files in those sub-directories and configure those
sub-directories in module descriptor of the application.
package com.tutorialspoint.client;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.Window;
25
GWT
You can create more Java files in the same source directory to define either entry points or
to define helper routines.
Keep the default values intact and click Compile button. If everything goes fine, you will see
following output in Eclipse console
26
GWT
If everything is fine, you must see GWT Development Mode active in Eclipse containing a URL
as shown below. Double click the URL to open the GWT application.
Because you are running your application in development mode, you will also need to install
GWT plugin for your browser. Simply follow the onscreen instructions to install the plugin.
If you already have GWT plugin set for your browser, then you should be able to see the
following output
27
GWT
Congratulations! You have implemented your first application using Google Web Toolkit
(GWT).
28
5. GWT - DEPLOY APPLICATION GWT
This tutorial will explain you how to create an application “war” file and how to deploy that
in Apache Tomcat Websever root.
If you understood this simple example, then you will also be able to deploy a complex GWT
application following similar steps.
Now, let us have a working Eclipse IDE along with GWT plugin place and follow certain steps
to create a GWT application:
Step Description
3 Compile and run the application to make sure business logic is working as per
the requirements.
4 Finally, zip the content of the war folder of the application in the form of war file
and deploy it in Apache Tomcat Webserver.
5 Launch your web application using appropriate URL as explained below in the
last step.
29
GWT
</module>
body {
text-align: center;
font-family: verdana, sans-serif;
}
h1 {
font-size: 2em;
font-weight: bold;
color: #777777;
margin: 40px 0px 70px;
text-align: center;
}
<html>
<head>
<title>Hello World</title>
<link rel="stylesheet" href="HelloWorld.css"/>
<script language="javascript" src="helloworld/helloworld.nocache.js">
</script>
</head>
30
GWT
<body>
<h1>Hello World</h1>
<div id="gwtContainer"></div>
</body>
</html>
I modified the HTML a little bit from the previous example. Here I created a placeholder
<div>...</div> where we will insert some content using our entry point java class. So let us
have the following content of Java file src/com.tutorialspoint/HelloWorld.java.
package com.tutorialspoint.client;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.RootPanel;
RootPanel.get("gwtContainer").add(html);
}
}
Here we created a basic widget HTML and added it inside the div tag having the
id="gwtContainer". We will study different GWT widgets in the coming chapters.
Once you are ready with all the changes done, let us compile and run the application in
development mode as we did in GWT - Create Application chapter. If everything is fine with
your application, then this will produce the following result:
31
GWT
Server name (localhost) and port (8080) may vary as per your tomcat configuration.
32
GWT
33
6. GWT - STYLE WITH CSS GWT
GWT widgets rely on cascading style sheets (CSS) for visual styling. By default, the class
name for each component is gwt-<classname>.
For example, the Button widget has a default style of gwt-Button and similar way the TextBox
widgest has a default style of gwt-TextBox.
In order to give all buttons and text boxes a larger font, you could put the following rule in
your application's CSS file
By default, neither the browser nor GWT creates default id attributes for widgets. You must
explicitly create a unique id for the elements which you can use in CSS. In order to give a
particular button with id my-button-id a larger font, you could put the following rule in your
application's CSS file
To set the id for a GWT widget, retrieve its DOM Element and then set the id attribute as
follows:
This method will clear any existing styles and set the widget style to the new
CSS class provided using style.
34
GWT
This method will add a secondary or dependent style name to the widget. A
secondary style name is an additional style name that is,so if there were any
previous style names applied they are kept.
This method will remove given style from the widget and leaves any others
associated with the widget.
This method gets all of the object's style names, as a space-separated list.
This method sets the object's primary style name and updates all dependent
style names.
For example, let's define two new styles which we will apply to a text
.gwt-Big-Text{
font-size:150%;
}
.gwt-Small-Text{
font-size:75%;
}
.gwt-Red-Text{
color:red;
}
Now you can use setStyleName(Style) to change the default setting to new setting. After
applying the following rule, a text's font will become large
txtWidget.setStyleName("gwt-Big-Text");
We can apply a secondary CSS rule on the same widget to change its color as follows:
txtWidget.addStyleName("gwt-Red-Text");
Using the above method, you can add as many styles as you like to apply on a widget. If you
remove the first style from the button widget, then the second style will still remain with the
text.
35
GWT
txtWidget.removeStyleName("gwt-Big-Text");
The final appearance of a widget is determined by the sum of all the secondary styles added
to it, plus its primary style. You set the primary style of a widget with the
setStylePrimaryName(String) method. To illustrate, let's say we have a Label widget. In our
CSS file, we have the following rules defined:
.MyText {
color: blue;
}
.BigText {
font-size: large;
}
.LoudText {
font-weight: bold;
}
Let's suppose we want a particular label widget to always display blue text, and in some cases,
use a larger, bold font for added emphasis.
36
GWT
someText.addStyleName("BigText");
someText.addStyleName("LoudText");
...
Step Description
3 Compile and run the application to verify the result of the implemented logic.
<module rename-to='helloworld'>
<!-- Inherit the core Web Toolkit stuff. -->
<inherits name='com.google.gwt.user.User'/>
</module>
body{
text-align: center;
font-family: verdana, sans-serif;
}
h1{
font-size: 2em;
font-weight: bold;
color: #777777;
margin: 40px 0px 70px;
text-align: center;
}
.gwt-Button{
font-size: 150%;
38
GWT
font-weight: bold;
width:100px;
height:100px;
}
.gwt-Big-Text{
font-size:150%;
}
.gwt-Small-Text{
font-size:75%;
}
<html>
<head>
<title>Hello World</title>
<link rel="stylesheet" href="HelloWorld.css"/>
<script language="javascript" src="helloworld/helloworld.nocache.js">
</script>
</head>
<body>
</body>
</html>
39
GWT
package com.tutorialspoint.client;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.RootPanel;
RootPanel.get("gwtGreenButton").add(Btn1);
RootPanel.get("gwtRedButton").add(Btn2);
40
GWT
}
}
Once you are ready with all the changes done, let us compile and run the application in
development mode as we did in GWT - Create Application chapter. If everything is fine with
your application, this will produce following result:
Now try clicking on the two buttons displayed and observe "Hello, World!" text which keeps
changing its font upon clicking on the two buttons.
41
7. GWT - BASIC WIDGETS GWT
UI elements : These are the core visual elements the user eventually sees and
interacts with. GWT provides a huge list of widely used and common elements varying
from basic to complex, which we will cover in this tutorial.
Layouts: They define how UI elements should be organized on the screen and provide
a final look and feel of the GUI (Graphical User Interface). This part will be covered in
Layout chapter.
Behavior: These are events which occur when the user interacts with UI elements.
This part will be covered in Event Handling chapter.
GWT UI Elements
The GWT library provides classes in a well-defined class hierarchy to create complex web-
based user interfaces. All classes in this component hierarchy has been derived from the
UIObject base class as shown below:
Every Basic UI widget inherits properties from a Widget class which in turn inherits properties
from UIObject. Tree and Menu will be covered in “Complex widgets” tutorial later.
42
GWT
This widget can contain HTML text and displays the html content using a <div>
element, causing it to be displayed with block layout.
Introduction
The class UIObject is the superclass for all user-interface objects. It simply wraps a DOM
element, and cannot receive events. It provides direct child classes like Widget, MenuItem,
MenuItemSeparator, TreeItem.
Class Declaration
Following is the declaration for com.google.gwt.user.client.ui.UIObject class:
Field
Following are the fields for com.google.gwt.user.client.ui.UIObject class:
43
GWT
Class Constructors
S.No. Constructor & Description
1 UIObject()
Class Methods
S.No. Method & Description
Ensure that elem has an ID property set, which allows it to integrate with third-
party libraries and test tools.
5 ensureDebugId(java.lang.String id)
Ensure that the main Element for this UIObject has an ID property set, which
allows it to integrate with third-party libraries and test tools.
6 int getAbsoluteLeft()
Gets the object's absolute left position in pixels, as measured from the browser
window's client area.
44
GWT
7 int getAbsoluteTop()
Gets the object's absolute top position in pixels, as measured from the browser
window's client area.
8 Element getElement()
9 int getOffsetHeight()
10 int getOffsetWidth()
Template method that returns the element to which style names will be applied.
12 java.lang.String getStyleName()
14 java.lang.String getStylePrimaryName()
16 java.lang.String getTitle()
17 boolean isVisible()
45
GWT
Called when the user sets the id using the ensureDebugId(String) method.
Sets the object's size, in pixels, not including decorations such as border,
margin, and padding.
Clears all of the element's style names and sets it to the given style.
46
GWT
This convenience method adds or removes a style name for a given element.
Clears all of the object's style names and sets it to the given style.
Sets the element's primary style name and updates all dependent style names.
Sets the object's primary style name and updates all dependent style names.
36 java.lang.String toString()
This method is overridden so that any object can be viewed in the debugger as
an HTML snippet.
47
GWT
Methods Inherited
This class inherits methods from the following classes:
java.lang.Object
Introduction
The class Widget is the base class for the majority of user-interface objects. Widget adds
support for receiving events from the browser and being added directly to panels.
Class Declaration
Following is the declaration for com.google.gwt.user.client.ui.Widget class:
Field
Following are the fields for com.google.gwt.user.client.ui.Widget class:
Class Constructors
S.No. Constructor & Description
1 Widget()
48
GWT
Class Methods
S.No. Method & Description
Adds a native event handler to the widget and sinks the corresponding native
event.
49
GWT
50