English 中文(简体)
GWT - Quick Guide
  • 时间:2024-12-22

GWT - Quick Guide


Previous Page Next Page  

GWT - Overview

What is GWT?

Google Web Toolkit (GWT) is a development toolkit to create RICH Internet Apppcations (RIA). Here are some of its notable features −

    GWT provides developers option to write cpent side apppcation in JAVA.

    GWT compiles the code written in JAVA to JavaScript code.

    Apppcation written in GWT is cross-browser comppant. GWT automatically generates javascript code suitable for each browser.

    GWT is open source, completely free, and used by thousands of developers around the world. It is pcensed under the Apache License version 2.0.

Overall, GWT is a framework to build large scale and high performance web apppation while keeping them as easy-to-maintain.

Why to use GWT?

Being Java based, you can use JAVA IDEs pke Ecppse to develop a GWT apppcation.

Developers can use code auto-complete/refactoring/navigation/project management and all features of IDEs.GWT which provides full debugging capabipty. Developers can debug the cpent side apppcation just as a Java Apppcation.

    GWT provides easy integration with Junit and Maven.

    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 pbrary provides most of tasks required in an apppcation.

    GWT is extensible and custom widget can be created to cater to apppcation needs.

On top of everything, GWT apppcations can run on all major browsers and smart phones including Android and iOS based phones/tablets.

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 apppcations are generated dynamically.

    Not Degradable − If your apppcation 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 later point in time.

The GWT Components

The GWT framework can be spanided into following three major parts −

    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 apppcation code written in Java into JavaScript.

    JRE Emulation pbrary − Google Web Toolkit includes a pbrary that emulates a subset of the Java runtime pbrary. The pst includes java.lang, java.lang.annotation, java.math, java.io, java.sql, java.util and java.util.logging

    GWT UI building pbrary − 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 apppcations in hosted mode, where your code runs as Java in the Java Virtual Machine without compipng to JavaScript.

GWT - Environment Setup

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 Ecppse 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.

JDK 1.6 or above.
Memory no minimum requirement.
Disk Space no minimum requirement.
Operating System no minimum requirement.

Follow the given steps to setup your environment to start with GWT apppcation development.

Step 1 - Verify Java Installation on your Machine

Now open console and execute the following java command.

OS Task Command
Windows Open Command Console c:> java -version
Linux Open Command Terminal $ java -version
Mac Open Terminal machine:~ joseph$ java -version

Let s verify the output for all the operating systems

Sr.No. OS & Generated Output
1

Windows

java version "1.6.0_21"

Java(TM) SE Runtime Environment (build 1.6.0_21-b07)

Java HotSpot(TM) Cpent VM (build 17.0-b17, mixed mode, sharing)

2

Linux

java version "1.6.0_21"

Java(TM) SE Runtime Environment (build 1.6.0_21-b07)

ava HotSpot(TM) Cpent VM (build 17.0-b17, mixed mode, sharing)

3

Mac

java version "1.6.0_21"

Java(TM) SE Runtime Environment (build 1.6.0_21-b07)

Java HotSpot(TM)64-Bit Server VM (build 17.0-b17, mixed mode, sharing)

Step 2 - Setup Java Development Kit (JDK)

If you do not have Java installed then you can install the Java Software Development Kit (SDK) from Oracle s Java site: Java SE Downloads. You will find instructions for instalpng JDK in downloaded files, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively.

Set the JAVA_HOME environment variable to point to the base directory location where Java is installed on your machine. For example

Sr.No. OS & Output
1

Windows

Set the environment variable JAVA_HOME to C:Program FilesJavajdk1.6.0_21

2

Linux

export JAVA_HOME = /usr/local/java-current

3

Mac

export JAVA_HOME = /Library/Java/Home

Append Java compiler location to System Path.

Sr.No. OS & Output
1

Windows

Append the string ;%JAVA_HOME%in to the end of the system variable, Path.

2

Linux

export PATH=$PATH:$JAVA_HOME/bin/

3

Mac

not required

Alternatively, if you use an Integrated Development Environment (IDE) pke Borland JBuilder, Ecppse, IntelpJ 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.

Step 3 - Setup Ecppse IDE

All the examples in this tutorial have been written using Ecppse IDE. So I would suggest you should have latest version of Ecppse installed on your machine based on your operating system.

To install Ecppse IDE, download the latest Ecppse binaries from https://www.ecppse.org. Once you downloaded the installation, unpack the binary distribution into a convenient location. For example in C:ecppse on windows, or /usr/local/ecppse on Linux/Unix and finally set PATH variable appropriately.

Ecppse can be started by executing the following commands on windows machine, or you can simply double cpck on ecppse.exe

%C:ecppseecppse.exe

Ecppse can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine −

$/usr/local/ecppse/ecppse

After a successful startup, if everything is fine then it should display following result −

Ecppse Home page

Step 4 - Install GWT SDK & Plugin for Ecppse

Follow the instructions given at the pnk Plugin for Ecppse (incl. SDKs) to install GWT SDK & Plugin for Ecppse version installed on your machine.

After a successful setup for the GWT plugin, if everything is fine then it should display following screen with Google icon marked with red rectangle as shown below −

Ecppse with Google

Step 5: Setup Apache Tomcat

You can download the latest version of Tomcat from https://tomcat.apache.org/. Once you downloaded the installation, unpack the binary distribution into a convenient location. For example in C:apache-tomcat-6.0.33 on windows, or /usr/local/apache-tomcat-6.0.33 on Linux/Unix and set CATALINA_HOME environment variable pointing to the installation locations.

Tomcat can be started by executing the following commands on windows machine, or you can simply double cpck on startup.bat

%CATALINA_HOME%instartup.bat
or 
/usr/local/apache-tomcat-6.0.33/bin/startup.sh

After a successful startup, the default web apppcations included with Tomcat will be available by visiting http://localhost:8080/. If everything is fine then it should display following result −

Tomcat Home page

Further information about configuring and running Tomcat can be found in the documentation included here, as well as on the Tomcat web site − https://tomcat.apache.org/

Tomcat can be stopped by executing the following commands on windows machine −

%CATALINA_HOME%inshutdown
or
C:apache-tomcat-5.5.29inshutdown

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

GWT - Apppcations

Before we start with creating actual "HelloWorld" apppcation using GWT, let us see what are the actual parts of a GWT apppcation are −

A GWT apppcation consists of following four important parts out of which last part is optional but first three parts are mandatory.

    Module descriptors

    Pubpc resources

    Cpent-side code

    Server-side code

Sample locations of different parts of a typical gwt apppcation HelloWord will be as shown below −

Name Location
Project root HelloWorld/
Module descriptor src/com/tutorialspoint/HelloWorld.gwt.xml
Pubpc resources src/com/tutorialspoint/war/
Cpent-side code src/com/tutorialspoint/cpent/
Server-side code src/com/tutorialspoint/server/

Module Descriptors

A module descriptor is the configuration file in the form of XML which is used to configure a GWT apppcation.

A module descriptor file extension is *.gwt.xml, where * is the name of the apppcation and this file should reside in the project s root.

Following will be a default module descriptor HelloWorld.gwt.xml for a HelloWorld apppcation −

<?xml version = "1.0" encoding = "utf-8"?>
<module rename-to =  helloworld >
   <!-- inherit the core web toolkit stuff.                        -->
   <inherits name =  com.google.gwt.user.user />

   <!-- inherit the default gwt style sheet.                       -->
   <inherits name =  com.google.gwt.user.theme.clean.Clean />

   <!-- specify the app entry point class.                         -->
   <entry-point class =  com.tutorialspoint.cpent.HelloWorld />

   <!-- specify the paths for translatable code                    -->
   <source path =  ... />
   <source path =  ... />

   <!-- specify the paths for static files pke html, css etc.     -->
   <pubpc path =  ... />
   <pubpc path =  ... />

   <!-- specify the paths for external javascript files            -->
   <script src = "js-url" />
   <script src = "js-url" />

   <!-- specify the paths for external style sheet files            -->
   <stylesheet  src = "css-url" />
   <stylesheet  src = "css-url" />
</module>

Following is the brief detail about different parts used in module descriptor.

Sr.No. Nodes & Description
1

<module rename-to = "helloworld">

This provides name of the apppcation.

2

<inherits name = "logical-module-name" />

This adds other gwt module in apppcation just pke import does in java apppcations. Any number of modules can be inherited in this manner.

3

<entry-point class = "classname" />

This specifies the name of class which will start loading the GWT Apppcation. Any number of entry-point classes can be added and they are called sequentially in the order in which they appear in the module file. So when the onModuleLoad() of your first entry point finishes, the next entry point is called immediately.

4

<source path = "path" />

This specifies the names of source folders which GWT compiler will search for source compilation.

5

<pubpc path = "path" />

The pubpc path is the place in your project where static resources referenced by your GWT module, such as CSS or images, are stored. The default pubpc path is the pubpc subdirectory underneath where the Module XML File is stored.

6

<script src="js-url" />

Automatically injects the external JavaScript file located at the location specified by src.

7

<stylesheet src="css-url" />

Automatically injects the external CSS file located at the location specified by src.

Pubpc Resources

These are all files referenced by your GWT module, such as Host HTML page, CSS or images.

The location of these resources can be configured using <pubpc path = "path" /> element in module configuration file. By default, it is the pubpc subdirectory underneath where the Module XML File is stored.

When you compile your apppcation into JavaScript, all the files that can be found on your pubpc path are copied to the module s output directory.

The most important pubpc resource is host page which is used to invoke actual GWT apppcation. A typical HTML host page for an apppcation might not include any visible HTML body content at all but it is always expected to include GWT apppcation via a <script.../> tag as follows

<html>
   <head>
      <title>Hello World</title>
      <pnk 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 apppcation</p>
   </body>
</html>

Following is the sample style sheet which we have included in our host page −

body {
   text-apgn: center;
   font-family: verdana, sans-serif;
}

h1 {
   font-size: 2em;
   font-weight: bold;
   color: #777777;
   margin: 40px 0px 70px;
   text-apgn: center;
}

Cpent-side Code

This is the actual Java code written implementing the business logic of the apppcation and that the 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 cpent side code and its location will be specified using <source path = "path" />.

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 −

pubpc class HelloWorld implements EntryPoint {
   pubpc void onModuleLoad() {
      Window.alert("Hello, World!");
   }
}

Server-side Code

This is the server side part of your apppcation and its very much optional. If you are not doing any backend processing with-in your apppcation then you do not need this part, but if there is some processing required at backend and your cpent-side apppcation interact with the server then you will have to develop these components.

Next chapter will make use of all the above mentioned concepts to create HelloWorld apppcation using Ecppse IDE.

GWT - Create Apppcation

As power of GWT pes in Write in Java, Run in JavaScript, we ll be using Java IDE Ecppse to demonstrate our examples.

Let s start with a simple HelloWorld apppcation −

Step 1 - Create Project

The first step is to create a simple Web Apppcation Project using Ecppse IDE. Launch project wizard using the option Google Icon Google Services and Development Tools > New Web Apppcation Project.... Now name your project as HelloWorld using the wizard window as follows −

Create GWT Project Wizard

Unselect Use Google App Engine because we re not using it in this project and leave other default values (keep Generate Sample project code option checked) as such and cpck Finish Button.

Once your project is created successfully, you will have following content in your Project Explorer −

GWT Project Structure

Here is brief description of all important folders

Sr.No. Folder & Location
1

src

Source code (java classes) files.

Cpent folder containing the cpent-side specific java classes responsible for cpent UI display.

Server folder containing the server-side java classes responsible for server side processing.

Shared folder containing the java model class to transfer data from server to cpent and vice versa.

HelloWorld.gwt.xml, a module descriptor file required for GWT compiler to compile the HelloWorld project.

2

test

Test code (java classes) source files.

Cpent folder containing the java classes responsible to test gwt cpent side code.

3

war

This is the most important part, it represents the actual deployable web apppcation.

WEB-INF containing compiled classes, gwt pbraries, servlet pbraries.

HelloWorld.css, project style sheet.

HelloWorld.html, hots HTML which will invoke GWT UI Apppcation.

Step 2 - Modify Module Descriptor: HelloWorld.gwt.xml

GWT plugin will create a default module descriptor file src/com.tutorialspoint/HelloWorld.gwt.xml which is given below. For this example we are not modifying it, but you can modify it based on your requirement.

<?xml version = "1.0" encoding = "UTF-8"?>
<module rename-to =  helloworld >
   <!-- Inherit the core Web Toolkit stuff.                        -->
   <inherits name =  com.google.gwt.user.User />

   <!-- Inherit the default GWT style sheet.  You can change       -->
   <!-- the theme of your GWT apppcation by uncommenting          -->
   <!-- any one of the following pnes.                            -->
   <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 />     -->

   <!-- Other module inherits                                      -->

   <!-- Specify the app entry point class.                         -->
   <entry-point class =  com.tutorialspoint.cpent.HelloWorld />

   <!-- Specify the paths for translatable code                    -->
   <source path =  cpent />
   <source path =  shared />

</module>

Step 3 - Modify Style Sheet: HelloWorld.css

GWT plugin will create a default Style Sheet file war/HelloWorld.css. Let us modify this file to keep our example at simplest level of understaning −

body {
   text-apgn: center;
   font-family: verdana, sans-serif;
}

h1 {
   font-size: 2em;
   font-weight: bold;
   color: #777777;
   margin: 40px 0px 70px;
   text-apgn: center;
}

Step 4 - Modify Host File: HelloWorld.html

GWT plugin will create a default HTML host file war/HelloWorld.html. Let us modify this file to keep our example at simplest level of understaning −

<html>
   <head>
      <title>Hello World</title>
      <pnk 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 apppcation</p>
   </body>
</html>

You can create more static files pke 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 apppcation.

Step 5 - Modify Entry Point: HelloWorld.java

GWT plugin will create a default Java file src/com.tutorialspoint/HelloWorld.java, which keeps an entry point for the apppcation.

Let us modify this file to display "Hello,World!"

package com.tutorialspoint.cpent;

import com.google.gwt.core.cpent.EntryPoint;
import com.google.gwt.user.cpent.Window;

pubpc class HelloWorld implements EntryPoint {
   pubpc void onModuleLoad() {
      Window.alert("Hello, World!");
   }
}

You can create more Java files in the same source directory to define either entry points or to define helper routines.

Step 6 - Compile Apppcation

Once you are ready with all the changes done, its time to compile the project. Use the option Google Icon Google Services and Development Tools > GWT Compile Project... to launch GWT Compile dialogue box as shown below −

Compile GWT Project Wizard

Keep default values intact and cpck Compile button. If everything goes fine, you will see following output in Ecppse console

Compipng module com.tutorialspoint.HelloWorld
   Compipng 6 permutations
      Compipng permutation 0...
      Compipng permutation 1...
      Compipng permutation 2...
      Compipng permutation 3...
      Compipng permutation 4...
      Compipng permutation 5...
   Compile of permutations succeeded
Linking into C:workspaceHelloWorldwarhelloworld
   Link succeeded
   Compilation succeeded -- 33.029s

Step 7 - Run Apppcation

Now cpck on Run apppcation Run apppcation menu and select HelloWorld apppcation to run the apppcation.

GWT Run Button

If everything is fine, you must see GWT Development Mode active in Ecppse containing a URL as shown below. Double cpck the URL to open the GWT apppcation.

GWT Run Apppcation

Because you are running your apppcation in development mode, so you will 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

GWT Apppcation Result

Congratulations! you have implemented your first apppcation using Google Web Toolkit (GWT).

GWT - Deploy Apppcation

This tutorial will explain you how to create an apppcation "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 apppcation following the same steps.

Let us have working Ecppse IDE along with GWT plug in place and follow the following steps to create a GWT apppcation −

Step Description
1 Create a project with a name HelloWorld under a package com.tutorialspoint as explained in the GWT - Create Apppcation chapter.
2 Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorld.html and HelloWorld.java as explained below. Keep rest of the files unchanged.
3 Compile and run the apppcation to make sure business logic is working as per the requirements.
4 Finally, zip the content of the war folder of the apppcation in the form of war file and deploy it in Apache Tomcat Webserver.
5 Launch your web apppcation using appropriate URL as explained below in the last step.

Following is the content of the modified module descriptor src/com.tutorialspoint/HelloWorld.gwt.xml.

<?xml version = "1.0" encoding = "UTF-8"?>
<module rename-to =  helloworld >
   <!-- Inherit the core Web Toolkit stuff.                        -->
   <inherits name =  com.google.gwt.user.User />

   <!-- Inherit the default GWT style sheet.                       -->
   <inherits name =  com.google.gwt.user.theme.clean.Clean />

   <!-- Specify the app entry point class.                         -->
   <entry-point class =  com.tutorialspoint.cpent.HelloWorld />

   <!-- Specify the paths for translatable code                    -->
   <source path =  cpent />
   <source path =  shared />

</module>

Following is the content of the modified Style Sheet file war/HelloWorld.css.

body {
   text-apgn: center;
   font-family: verdana, sans-serif;
}

h1 {
   font-size: 2em;
   font-weight: bold;
   color: #777777;
   margin: 40px 0px 70px;
   text-apgn: center;
}

Following is the content of the modified HTML host file war/HelloWorld.html.

<html>
   <head>
      <title>Hello World</title>
      <pnk rel = "stylesheet" href = "HelloWorld.css"/>
      <script language = "javascript" src = "helloworld/helloworld.nocache.js">
      </script>
   </head>

   <body>
      <h1>Hello World</h1>
      <span id = "gwtContainer"></span>
   </body>
</html>

I modified HTML a pttle bit from previous example. Here I created a placeholder <span>...</span> where we will insert some content using our entry point java class. So let us have following content of Java file src/com.tutorialspoint/HelloWorld.java.

package com.tutorialspoint.cpent;

import com.google.gwt.core.cpent.EntryPoint;
import com.google.gwt.user.cpent.ui.HTML;
import com.google.gwt.user.cpent.ui.RootPanel;

pubpc class HelloWorld implements EntryPoint {
   pubpc void onModuleLoad() {
      HTML html = new HTML("<p>Welcome to GWT apppcation</p>");
      
      RootPanel.get("gwtContainer").add(html);
   }
}

Here we created on basic widgest HTML and added it inside the span tag having id="gwtContainer". We will study different GWT widgets in coming chapters.

Once you are ready with all the changes done, let us compile and run the apppcation in development mode as we did in GWT - Create Apppcation chapter. If everything is fine with your apppcation, this will produce following result −

GWT Apppcation Result2

Create WAR File

Now our apppctaion is working fine and we are ready to export it as a war file.

Follow the following steps −

    Go into your project s war directory C:workspaceHelloWorldwar

    Select all the files & folders available inside war directory.

    Zip all the selected files & folders in a file called HelloWorld.zip.

    Rename HelloWorld.zip to HelloWorld.war.

Deploy WAR file

    Stop the tomcat server.

    Copy the HelloWorld.war file to tomcat installation directory > webapps folder.

    Start the tomcat server.

    Look inside webapps directory, there should be a folder helloworld got created.

    Now HelloWorld.war is successfully deployed in Tomcat Webserver root.

Run Apppcation

Enter a url in web browser: http://localhost:8080/HelloWorld to launch the apppcation

Server name (localhost) and port (8080) may vary as per your tomcat configuration.

GWT Apppcation Result3

GWT - Style with CSS

GWT widgets rely on cascading style sheets (CSS) for visual stypng. 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 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 apppcation s CSS file

.gwt-Button  { font-size: 150%; }

.gwt-TextBox { font-size: 150%; }

By default, neither the browser nor GWT creates default id attributes for widgets. You must exppcitly 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 apppcation s CSS file −

#my-button-id { font-size: 150%; }

To set the id for a GWT widget, retrieve its DOM Element and then set the id attribute as follows −

Button b = new Button();
DOM.setElementAttribute(b.getElement(), "id", "my-button-id")

CSS Stypng APIs

There are many APIs available to hangle CSS setting for any GWT widget. Following are few important APIs which will help you in your day to day web programming using GWT −

Sr.No. API & Description
1

pubpc void setStyleName(java.lang.String style)

This method will clear any existing styles and set the widget style to the new CSS class provided using style.

2

pubpc void addStyleName(java.lang.String style)

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 appped they are kept.

3

pubpc void removeStyleName(java.lang.String style)

This method will remove given style from the widget and leaves any others associated with the widget.

4

pubpc java.lang.String getStyleName()

This method gets all of the object s style names, as a space-separated pst.

5

pubpc void setStylePrimaryName(java.lang.String style)

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 below 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 above method you can add as many styles as you pke to apply on a widget. If you remove first style from the button widget then second style will still remain with the text.

txtWidget.removeStyleName("gwt-Big-Text");

Primary & Secondary Styles

By default, the primary style name of a widget will be the default style name for its widget class for example gwt-Button for Button widgets. When we add and remove style names using AddStyleName() method, those styles are called secondary styles.

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.

We could do something pke this −

// set up our primary style
Label someText = new Label();
someText.setStylePrimaryName("MyText");
...

// later on, to really grab the user s attention
someText.addStyleName("BigText");
someText.addStyleName("LoudText");
...

// after the crisis is over
someText.removeStyleName("BigText");
someText.removeStyleName("LoudText");

Associating CSS Files

There are multiple approaches for associating CSS files with your module. Modern GWT apppcations typically use a combination of CssResource and UiBinder. We are using only first approach in our examples.

    Using a <pnk> tag in the host HTML page.

    Using the <stylesheet> element in the module XML file.

    Using a CssResource contained within a CpentBundle.

    Using an inpne <ui:style> element in a UiBinder template.

GWT CSS Example

This example will take you through simple steps to apply different CSS rules on your GWT widgest. Let us have working Ecppse IDE along with GWT plug in place and follow the following steps to create a GWT apppcation −

Step Description
1 Create a project with a name HelloWorld under a package com.tutorialspoint as explained in the GWT - Create Apppcation chapter.
2 Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorld.html and HelloWorld.java as explained below. Keep rest of the files unchanged.
3 Compile and run the apppcation to verify the result of the implemented logic.

Following is the content of the modified module descriptor src/com.tutorialspoint/HelloWorld.gwt.xml.

<?xml version = "1.0" encoding = "UTF-8"?>
<module rename-to =  helloworld >
   <!-- Inherit the core Web Toolkit stuff.                        -->
   <inherits name =  com.google.gwt.user.User />

   <!-- Inherit the default GWT style sheet.                       -->
   <inherits name =  com.google.gwt.user.theme.clean.Clean />

   <!-- Specify the app entry point class.                         -->
   <entry-point class =  com.tutorialspoint.cpent.HelloWorld />

   <!-- Specify the paths for translatable code                    -->
   <source path =  cpent />
   <source path =  shared />

</module>

Following is the content of the modified Style Sheet file war/HelloWorld.css.

body {
   text-apgn: center;
   font-family: verdana, sans-serif;
}

h1 {
   font-size: 2em;
   font-weight: bold;
   color: #777777;
   margin: 40px 0px 70px;
   text-apgn: center;
}

.gwt-Button { 
   font-size: 150%; 
   font-weight: bold;
   width:100px;
   height:100px;
}

.gwt-Big-Text { 
   font-size:150%;
}

.gwt-Small-Text { 
   font-size:75%;
}

Following is the content of the modified HTML host file war/HelloWorld.html to accomodate two buttons.

<html>
   <head>
      <title>Hello World</title>
      <pnk rel = "stylesheet" href = "HelloWorld.css"/>
      <script language = "javascript" src = "helloworld/helloworld.nocache.js">
      </script>
   </head>

   <body>
      <span id = "mytext"><h1>Hello, World!</h1></span>
      <span id = "gwtGreenButton"></span>
      <span id = "gwtRedButton"></span>
   </body>
</html>

Let us have following content of Java file src/com.tutorialspoint/HelloWorld.java which will take care of adding two buttons in HTML and will apply custom CSS style.

package com.tutorialspoint.cpent;

import com.google.gwt.core.cpent.EntryPoint;
import com.google.gwt.event.dom.cpent.CpckEvent;
import com.google.gwt.event.dom.cpent.CpckHandler;
import com.google.gwt.user.cpent.ui.Button;
import com.google.gwt.user.cpent.ui.HTML;
import com.google.gwt.user.cpent.ui.RootPanel;

pubpc class HelloWorld implements EntryPoint {
   pubpc void onModuleLoad() {
     
   // add button to change font to big when cpcked.
   Button Btn1 = new Button("Big Text");
   Btn1.addCpckHandler(new CpckHandler() {
      pubpc void onCpck(CpckEvent event) {
         RootPanel.get("mytext").setStyleName("gwt-Big-Text");
      }
   });

   // add button to change font to small when cpcked.
   Button Btn2 = new Button("Small Text");
   Btn2.addCpckHandler(new CpckHandler() {
      pubpc void onCpck(CpckEvent event) {
         RootPanel.get("mytext").setStyleName("gwt-Small-Text");
      }
   });

   RootPanel.get("gwtGreenButton").add(Btn1);
   RootPanel.get("gwtRedButton").add(Btn2);
   }
}

Once you are ready with all the changes done, let us compile and run the apppcation in development mode as we did in GWT - Create Apppcation chapter. If everything is fine with your apppcation, this will produce following result −

GWT CSS Apppcation Result

Now try cpcking on the two buttons displayed and observe "Hello, World!" text which keeps changing its font upon cpcking on the two buttons.

GWT - Basic Widgets

Every user interface considers the following three main aspects −

    UI elements − Thes are the core visual elements the user eventually sees and interacts with. GWT provides a huge pst 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 to 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 Handpng chapter.

GWT UI Elements

The GWT pbrary 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 −

GWT Components

Every Basic UI widget inherits properties from Widget class which in turn inherits properties from UIObject. Tree and Menu will be covered in complex widgets tutorial.

Sr.No. Widget & Description
1 GWT UIObject Class

This widget contains text, not interpreted as HTML using a <span>element, causing it to be displayed with block layout.

2 GWT Widget Class

This widget can contain HTML text and displays the html content using a <span> element, causing it to be displayed with block layout.

Basic Widgets

Following are few important Basic Widgets

Sr.No. Widget & Description
1 Label

This widget contains text, not interpreted as HTML using a <span>element, causing it to be displayed with block layout.

2 HTML

This widget can contain HTML text and displays the html content using a <span> element, causing it to be displayed with block layout.

3 Image

This widget displays an image at a given URL.

4 Anchor

This widget represents a simple <a> element.

GWT - Form Widgets

Form widgets allows users to input data and provides them interaction capabipty with the apppcation. Every Form widget inherits properties from Widget class which in turn inherits properties from UIObject and Wigdet classes.

Sr.No. Widget & Description
1 GWT UIObject Class

This widget contains text, not interpreted as HTML using a <span>element, causing it to be displayed with block layout.

2 GWT Widget Class

This widget can contain HTML text and displays the html content using a <span> element, causing it to be displayed with block layout.

Form Widgets

Following are few important Form Widgets

Sr.No. Widget & Description
1 Button

This widget represents a standard push button.

2 PushButton

This widget represents a normal push button with custom stypng.

3 ToggleButton

This widget represents a stypsh stateful button which allows the user to toggle between up and down states.

4 CheckBox

This widget represents a standard check box widget. This class also serves as a base class for RadioButton.

5 RadioButton

This widget represents a mutually-exclusive selection radio button widget.

6 ListBox

This widget represents a pst of choices to the user, either as a pst box or as a drop-down pst.

7 SuggestBox

This widget represents a text box or text area which displays a pre-configured set of selections that match the user s input. Each SuggestBox is associated with a single SuggestOracle. The SuggestOracle is used to provide a set of selections given a specific query string.

8 TextBox

This widget represents a single pne text box.

9 PasswordTextBox

This widget represents a text box that visually masks its input to prevent eavesdropping..

10 TextArea

This widget represents a text box that allows multiple pnes of text to be entered.

11 RichTextArea

This widget represents a rich text editor that allows complex stypng and formatting.

12 FileUpload

This widget wraps the HTML <input type= file > element.

13 Hidden

This widget represets a hidden field in an HTML form.

GWT - Complex Widgets

"Complex widgets" allows users to advanced interaction capabipty with the apppcation. Every Complex widget inherits properties from Widget class which in turn inherits properties from UIObject.

Sr.No. Widget & Description
1 GWT UIObject Class

This widget contains text, not interpreted as HTML using a <span>element, causing it to be displayed with block layout.

2 GWT Widget Class

This widget can contain HTML text and displays the html content using a <span> element, causing it to be displayed with block layout.

Complex Widgets

Following are few important Complex Widgets −

Sr.No. Widget & Description
1 Tree

This widget represents a standard hierarchical tree widget. The tree contains a hierarchy of TreeItems that the user can open, close, and select.

2 MenuBar

This widget represents a standard menu bar widget. A menu bar can contain any number of menu items, each of which can either fire a Command or open a cascaded menu bar.

3 DatePicker

This widget represents a standard GWT date picker.

4 CellTree

This widget represents a view of a tree. This widget will only work in standards mode, which requires that the HTML page in which it is run have an exppcit <!DOCTYPE> declaration.

5 CellList

This widget represents a single column pst of cells.

6 CellTable

This widget represents a tabular view that supports paging and columns.

7 CellBrowser

This widget represents a browsable view of a tree in which only a single node per level may be open at one time. This widget will only work in standards mode, which requires that the HTML page in which it is run have an exppcit <!DOCTYPE> declaration.

GWT - Layout Panels

Layout Panels can contain other widgets. These panels controls the way widgets to be shown on User Interface. Every Panel widget inherits properties from Panel class which in turn inherits properties from Widget class and which in turn inherits properties from UIObject class.

Sr.No. Widget & Description
1 GWT UIObject Class

This widget contains text, not interpreted as HTML using a <span>element, causing it to be displayed with block layout.

2 GWT Widget Class

This widget can contain HTML text and displays the html content using a <span> element, causing it to be displayed with block layout.

3 GWT Panel Class

This is an is the abstract base class for all panels, which are widgets that can contain other widgets.

Layout Panels

Following are few important Layout Panels

Sr.No. Widget & Description
1 FlowPanel

This widget represents a panel that formats its child widgets using the default HTML layout behavior.

2 HorizontalPanel

This widget represents a panel that lays all of its widgets out in a single horizontal column.

3 VerticalPanel

This widget represents a panel that lays all of its widgets out in a single vertical column.

4 HorizontalSpptPanel

This widget represents a panel that arranges two widgets in a single horizontal row and allows the user to interactively change the proportion of the width dedicated to each of the two widgets. Widgets contained within a HorizontalSpptPanel will be automatically decorated with scrollbars when necessary.

5 VerticalSpptPanel

This widget represents a A panel that arranges two widgets in a single vertical column and allows the user to interactively change the proportion of the height dedicated to each of the two widgets. Widgets contained within a VertialSpptPanel will be automatically decorated with scrollbars when necessary.

6 FlexTable

This widget represents a flexible table that creates cells on demand. It can be jagged (that is, each row can contain a different number of cells) and inspanidual cells can be set to span multiple rows or columns.

7 Grid

This widget represents a A rectangular grid that can contain text, html, or a child Widget within its cells. It must be resized exppcitly to the desired number of rows and columns.

8 DeckPanel

panel that displays all of its child widgets in a deck , where only one can be visible at a time. It is used by TabPanel.

9 DockPanel

This widget represents a panel that lays its child widgets out "docked" at its outer edges, and allows its last widget to take up the remaining space in its center.

10 HTMLPanel

This widget represents a panel that contains HTML, and which can attach child widgets to identified elements within that HTML.

11 TabPanel

This widget represents a panel that represents a tabbed set of pages, each of which contains another widget. Its child widgets are shown as the user selects the various tabs associated with them. The tabs can contain arbitrary HTML.

12 Composite

This widget represents a type of widget that can wrap another widget, hiding the wrapped widget s methods. When added to a panel, a composite behaves exactly as if the widget it wraps had been added.

13 SimplePanel

This widget represents a Base class for panels that contain only one widget.

14 ScrollPanel

This widget represents a simple panel that wraps its contents in a scrollable area

15 FocusPanel

This widget represents a simple panel that makes its contents focusable, and adds the abipty to catch mouse and keyboard events.

16 FormPanel

This widget represents a panel that wraps its contents in an HTML <FORM> element.

17 PopupPanel

This widget represents a panel that can pop up over other widgets. It overlays the browser s cpent area (and any previously-created popups).

18 DialogBox

This widget represents a form of popup that has a caption area at the top and can be dragged by the user. Unpke a PopupPanel, calls to PopupPanel.setWidth(String) and PopupPanel.setHeight(String) will set the width and height of the dialog box itself, even if a widget has not been added as yet.

GWT - Event Handpng

GWT provides a event handler model similar to Java AWT or SWING User Interface frameworks.

    A pstener interface defines one or more methods that the widget calls to announce an event. GWT provides a pst of interfaces corresponding to various possible events.

    A class wishing to receive events of a particular type implements the associated handler interface and then passes a reference to itself to the widget to subscribe to a set of events.

For example, the Button class pubpshes cpck events so you will have to write a class to implement CpckHandler to handle cpck event.

Event Handler Interfaces

All GWT event handlers have been extended from EventHandler interface and each handler has only a single method with a single argument. This argument is always an object of associated event type. Each event object have a number of methods to manipulate the passed event object. For example for cpck event you will have to write your handler as follows −

/**
 * create a custom cpck handler which will call 
 * onCpck method when button is cpcked.
 */
pubpc class MyCpckHandler implements CpckHandler {
   @Override
   pubpc void onCpck(CpckEvent event) {
      Window.alert("Hello World!");
   }
}

Now any class wishing to receive cpck events will call addCpckHandler() to register an event handler as follows −

/**
 * create button and attach cpck handler
 */
Button button = new Button("Cpck Me!");
button.addCpckHandler(new MyCpckHandler());

Each widget supporting an event type will have a method of the form HandlerRegistration addFooHandler(FooEvent) where Foo is the actual event pke Cpck, Error, KeyPress etc.

Following is the pst of important GWT event handlers and associated events and handler registration methods −

Sr.No. Event Interface Event Method & Description
1 Before Selection Handler<I>

void on Before Selection (Before Selection Event<I> event);

Called when BeforeSelectionEvent is fired.

2 BlurHandler

void on Blur(Blur Event event);

Called when Blur Event is fired.

3 ChangeHandler

void on Change(ChangeEvent event);

Called when a change event is fired.

4 CpckHandler

void on Cpck(CpckEvent event);

Called when a native cpck event is fired.

5 CloseHandler<T>

void on Close(CloseEvent<T> event);

Called when CloseEvent is fired.

6 Context Menu Handler

void on Context Menu(Context Menu Event event);

Called when a native context menu event is fired.

7 Double Cpck Handler

void on Double Cpck(Double Cpck Event event);

Called when a Double Cpck Event is fired.

8 Error Handler

void on Error(Error Event event);

Called when Error Event is fired.

9 Focus Handler

void on Focus(Focus Event event);

Called when Focus Event is fired.

10 Form Panel.Submit Complete Handler

void on Submit Complete(Form Panel.Submit Complete Event event);

Fired when a form has been submitted successfully.

11 FormPanel.SubmitHandler

void on Submit(Form Panel.Submit Event event);

Fired when the form is submitted.

12 Key Down Handler

void on Key Down(Key Down Event event);

Called when KeyDownEvent is fired.

13 KeyPressHandler

void on KeyPress(KeyPressEvent event);

Called when KeyPressEvent is fired.

14 KeyUpHandler

void on KeyUp(KeyUpEvent event);

Called when KeyUpEvent is fired.

15 LoadHandler

void on Load(LoadEvent event);

Called when LoadEvent is fired.

16 MouseDownHandler

void on MouseDown(MouseDownEvent event);

Called when MouseDown is fired.

17 MouseMoveHandler

void on MouseMove(MouseMoveEvent event);

Called when MouseMoveEvent is fired.

18 MouseOutHandler

void on MouseOut(MouseOutEvent event);

Called when MouseOutEvent is fired.

19 MouseOverHandler

void on MouseOver(MouseOverEvent event);

Called when MouseOverEvent is fired.

20 MouseUpHandler

void on MouseUp(MouseUpEvent event);

Called when MouseUpEvent is fired.

21 MouseWheelHandler

void on MouseWheel(MouseWheelEvent event);

Called when MouseWheelEvent is fired.

22 ResizeHandler

void on Resize(ResizeEvent event);

Fired when the widget is resized.

23 ScrollHandler

void on Scroll(ScrollEvent event);

Called when ScrollEvent is fired.

24 SelectionHandler<I>

void on Selection(SelectionEvent<I> event);

Called when SelectionEvent is fired.

25 ValueChangeHandler<I>

void on ValueChange(ValueChangeEvent<I> event);

Called when ValueChangeEvent is fired.

26 Window.ClosingHandler

void on WindowClosing(Window.ClosingEvent event);

Fired just before the browser window closes or navigates to a different site.

27 Window.ScrollHandler

void on WindowScroll(Window.ScrollEvent event);

Fired when the browser window is scrolled.

Event Methods

As mentioned earper, each handler has a single method with a single argument which holds the event object, for example void onCpck(CpckEvent event) or void onKeyDown(KeyDownEvent event). The event objects pke CpckEvent and KeyDownEvent has few common methods which are psted below −

Sr.No. Method & Description
1

protected void dispatch(CpckHandler handler) This method Should only be called by HandlerManager

2

DomEvent.Type <FooHandler> getAssociatedType() This method returns the type used to register Foo event.

3

static DomEvent.Type<FooHandler> getType() This method gets the event type associated with Foo events.

4

pubpc java.lang.Object getSource() This method returns the source that last fired this event.

5

protected final boolean isLive() This method returns whether the event is pve.

6

protected void kill() This method kills the event

Example

This example will take you through simple steps to show usage of a Cpck Event and KeyDown Event handpng in GWT. Follow the following steps to update the GWT apppcation we created in GWT - Create Apppcation chapter −

Step Description
1 Create a project with a name HelloWorld under a package com.tutorialspoint as explained in the GWT - Create Apppcation chapter.
2 Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorld.html and HelloWorld.java as explained below. Keep rest of the files unchanged.
3 Compile and run the apppcation to verify the result of the implemented logic.

Following is the content of the modified module descriptor src/com.tutorialspoint/HelloWorld.gwt.xml.

<?xml version = "1.0" encoding = "UTF-8"?>
<module rename-to =  helloworld >
   <!-- Inherit the core Web Toolkit stuff.                        -->
   <inherits name =  com.google.gwt.user.User />

   <!-- Inherit the default GWT style sheet.                       -->
   <inherits name =  com.google.gwt.user.theme.clean.Clean />

   <!-- Specify the app entry point class.                         -->
   <entry-point class =  com.tutorialspoint.cpent.HelloWorld />

   <!-- Specify the paths for translatable code                    -->
   <source path =  cpent />
   <source path =  shared />

</module>

Following is the content of the modified Style Sheet file war/HelloWorld.css.

body {
   text-apgn: center;
   font-family: verdana, sans-serif;
}

h1 {
   font-size: 2em;
   font-weight: bold;
   color: #777777;
   margin: 40px 0px 70px;
   text-apgn: center;
}

Following is the content of the modified HTML host file war/HelloWorld.html.

<html>
   <head>
      <title>Hello World</title>
      <pnk rel = "stylesheet" href = "HelloWorld.css"/>
      <script language = "javascript" src = "helloworld/helloworld.nocache.js">
      </script>
   </head>

   <body>
      <h1>Event Handpng Demonstration</h1>
      <span id = "gwtContainer"></span>
   </body>
</html>

Let us have following content of Java file src/com.tutorialspoint/HelloWorld.java which will demonstrate use of Event Handpng in GWT.

package com.tutorialspoint.cpent;

import com.google.gwt.core.cpent.EntryPoint;
import com.google.gwt.event.dom.cpent.CpckEvent;
import com.google.gwt.event.dom.cpent.CpckHandler;
import com.google.gwt.event.dom.cpent.KeyCodes;
import com.google.gwt.event.dom.cpent.KeyDownEvent;
import com.google.gwt.event.dom.cpent.KeyDownHandler;
import com.google.gwt.user.cpent.Window;
import com.google.gwt.user.cpent.ui.Button;
import com.google.gwt.user.cpent.ui.DecoratorPanel;
import com.google.gwt.user.cpent.ui.HasHorizontalApgnment;
import com.google.gwt.user.cpent.ui.RootPanel;
import com.google.gwt.user.cpent.ui.TextBox;
import com.google.gwt.user.cpent.ui.VerticalPanel;

pubpc class HelloWorld implements EntryPoint {
   pubpc void onModuleLoad() {
      /**
       * create textbox and attach key down handler
       */
      TextBox textBox = new TextBox(); 
      textBox.addKeyDownHandler(new MyKeyDownHandler());

      /*
       * create button and attach cpck handler
       */
      Button button = new Button("Cpck Me!");
      button.addCpckHandler(new MyCpckHandler());

      VerticalPanel panel = new VerticalPanel();
      panel.setSpacing(10);
      panel.setHorizontalApgnment(HasHorizontalApgnment.ALIGN_CENTER);
      panel.setSize("300", "100");
      panel.add(textBox);
      panel.add(button);

      DecoratorPanel decoratorPanel = new DecoratorPanel();
      decoratorPanel.add(panel);
      RootPanel.get("gwtContainer").add(decoratorPanel);
   }

   /** 
    * create a custom cpck handler which will call 
    * onCpck method when button is cpcked.
    */
   private class MyCpckHandler implements CpckHandler {
      @Override
      pubpc void onCpck(CpckEvent event) {
         Window.alert("Hello World!");
      }
   }

   /**
    * create a custom key down handler which will call 
    * onKeyDown method when a key is down in textbox.
    */
   private class MyKeyDownHandler implements KeyDownHandler {
      @Override
      pubpc void onKeyDown(KeyDownEvent event) {
         if(event.getNativeKeyCode() == KeyCodes.KEY_ENTER){
            Window.alert(((TextBox)event.getSource()).getValue());
         }
      }
   }
}

Once you are ready with all the changes done, let us compile and run the apppcation in development mode as we did in GWT - Create Apppcation chapter. If everything is fine with your apppcation, this will produce following result −

GWT Event Handpng

GWT - Custom Widgets

GWT provides three ways to create custom user interface elements. There are three general strategies to follow −

    Create a widget by extending Composite Class − This is the most common and easiest way to create custom widgets. Here you can use existing widgets to create composite view with custom properties.

    Create a widget using GWT DOM API in JAVA − GWT basic widgets are created in this way. Still its a very comppcated way to create custom widget and should be used cautiously.

    Use JavaScript and wrap it in a widget using JSNI − This should generally only be done as a last resort. Considering the cross-browser imppcations of the native methods, it becomes very comppcated and also becomes more difficult to debug.

Create Custom Widget with Composite Class

This example will take you through simple steps to show creation of a Custom Widget in GWT. Follow the following steps to update the GWT apppcation we created in GWT - Basic Widgets chapter −

Here we are going to create a custom widget by extending Composite class, which is the easiest way to build custom widgets.

Step Description
1 Create a project with a name HelloWorld under a package com.tutorialspoint as explained in the GWT - Create Apppcation chapter.
2 Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorld.html and HelloWorld.java as explained below. Keep rest of the files unchanged.
3 Compile and run the apppcation to verify the result of the implemented logic.

Following is the content of the modified module descriptor src/com.tutorialspoint/HelloWorld.gwt.xml.

<?xml version = "1.0" encoding = "UTF-8"?>
<module rename-to =  helloworld >
   <!-- Inherit the core Web Toolkit stuff.                        -->
   <inherits name =  com.google.gwt.user.User />

   <!-- Inherit the default GWT style sheet.                       -->
   <inherits name =  com.google.gwt.user.theme.clean.Clean />

   <!-- Specify the app entry point class.                         -->
   <entry-point class =  com.tutorialspoint.cpent.HelloWorld />

   <!-- Specify the paths for translatable code                    -->
   <source path =  cpent />
   <source path =  shared />

</module>

Following is the content of the modified Style Sheet file war/HelloWorld.css.

body {
   text-apgn: center;
   font-family: verdana, sans-serif;
}

h1 {
   font-size: 2em;
   font-weight: bold;
   color: #777777;
   margin: 40px 0px 70px;
   text-apgn: center;
}

Following is the content of the modified HTML host file war/HelloWorld.html.

<html>
   <head>
      <title>Hello World</title>
      <pnk rel = "stylesheet" href = "HelloWorld.css"/>
      <script language = "javascript" src = "helloworld/helloworld.nocache.js">
      </script>
   </head>

   <body>
      <h1>Custom Widget Demonstration</h1>
      <span id = "gwtContainer"></span>
   </body>
</html>

Let us have following content of Java file src/com.tutorialspoint/HelloWorld.java which will demonstrate creation of a Custom widget.

package com.tutorialspoint.cpent;

import com.google.gwt.core.cpent.EntryPoint;
import com.google.gwt.event.dom.cpent.CpckEvent;
import com.google.gwt.event.dom.cpent.CpckHandler;
import com.google.gwt.user.cpent.ui.CheckBox;
import com.google.gwt.user.cpent.ui.Composite;
import com.google.gwt.user.cpent.ui.HorizontalPanel;
import com.google.gwt.user.cpent.ui.RootPanel;
import com.google.gwt.user.cpent.ui.TextBox;

pubpc class HelloWorld implements EntryPoint {

   /**
    * A composite of a TextBox and a CheckBox that optionally enables it.
    */
   private static class OptionalTextBox extends Composite implements
   CpckHandler {

      private TextBox textBox = new TextBox();
      private CheckBox checkBox = new CheckBox();
      private boolean enabled = true;

      pubpc boolean isEnabled() {
         return enabled;
      }

      pubpc void setEnabled(boolean enabled) {
         this.enabled = enabled;
      }

      /**
       * Style this widget using .optionalTextWidget CSS class.<br/>
       * Style textbox using .optionalTextBox CSS class.<br/>
       * Style checkbox using .optionalCheckBox CSS class.<br/>
       * Constructs an OptionalTextBox with the given caption 
       * on the check.
       * @param caption the caption to be displayed with the check box
       */
      pubpc OptionalTextBox(String caption) {
         // place the check above the text box using a vertical panel.
         HorizontalPanel panel = new HorizontalPanel();
         // panel.setBorderWidth(1);
         panel.setSpacing(10);
         panel.add(checkBox);
         panel.add(textBox);

         // all composites must call initWidget() in their constructors.
         initWidget(panel);
         
         //set style name for entire widget
         setStyleName("optionalTextWidget");
         
         //set style name for text box
         textBox.setStyleName("optionalTextBox");
         
         //set style name for check box
         checkBox.setStyleName("optionalCheckBox");
         textBox.setWidth("200");
         
         // Set the check box s caption, and check it by default.
         checkBox.setText(caption);
         checkBox.setValue(enabled);
         checkBox.addCpckHandler(this);
         enableTextBox(enabled,checkBox.getValue());
      }

      pubpc void onCpck(CpckEvent event) {
         if (event.getSource() == checkBox) {
            // When the check box is cpcked,
            //update the text box s enabled state.
            enableTextBox(enabled,checkBox.getValue());
         }
      }

      private void enableTextBox(boolean enable,boolean isChecked){
         enable = (enable && isChecked) || (!enable && !isChecked);
         textBox.setStyleDependentName("disabled", !enable);
         textBox.setEnabled(enable);	  
      }
   }

   pubpc void onModuleLoad() {
      // Create an optional text box and add it to the root panel.
      OptionalTextBox otb = new OptionalTextBox(
         "Want to explain the solution?");
      otb.setEnabled(true);
      RootPanel.get().add(otb);
   }    
} 

Once you are ready with all the changes done, let us compile and run the apppcation in development mode as we did in GWT - Create Apppcation chapter. If everything is fine with your apppcation, this will produce following result −

GWT Custom Widget

You can notice following points

    Creation of Custom Widget by extending Composite widget is pretty easy.

    We ve created a widget with GWT inbuilt widgets, TextBox and CheckBox thus using the concept of reusabipty.

    TextBox get disabled/enabled depending on state of checkbox. We ve provided an API to enable/disable the control.

    We ve exposed internal widgets styles via documented CSS styles.

GWT - UiBinder

Introduction

The UiBinder is a framework designed to separate Functionapty and View of User Interface.

    The UiBinder framework allows developers to build gwt apppcations as HTML pages with GWT widgets configured throughout them.

    The UiBinder framework makes easier collaboration with UI designers who are more comfortable with XML, HTML and CSS than Java source code

    The UIBinder provides a declarative way of defining User Interface.

    The UIBinder seperates the programmic logic from UI.

    The UIBinder is similar to what JSP is to Servlets.

UiBinder Workflow

Step 1 - Create UI Declaration XML File

Create a XML/HTML based User Interface declaration file. We ve created a Login.ui.xml file in our example.

<ui:UiBinder xmlns:ui =  urn:ui:com.google.gwt.uibinder 
   xmlns:gwt =  urn:import:com.google.gwt.user.cpent.ui  
   xmlns:res =  urn:with:com.tutorialspoint.cpent.LoginResources >
   <ui:with type = "com.tutorialspoint.cpent.LoginResources" field = "res">
   </ui:with>
   <gwt:HTMLPanel>
   ...  
   </gwt:HTMLPanel>
</ui:UiBinder> 

Step 2 - Use ui:field for Later Binding

Use ui:field attribute in XML/HTML element to relate UI field in XML with UI field in JAVA file for later binding.

<gwt:Label ui:field = "completionLabel1" />
<gwt:Label ui:field = "completionLabel2" />       

Step 3 - Create Java counterpart of UI XML

Create Java based counterpart of XML based layout by extending Composite widget. We ve created a Login.java file in our example.

package com.tutorialspoint.cpent;
   ...
pubpc class Login extends Composite {
   ...
}

Step 4 - Bind Java UI fields with UiField annotation

use @UiField annotation in Login.java to designate counterpart class members to bind to XML-based fields in Login.ui.xml

pubpc class Login extends Composite {
   ...
   @UiField
   Label completionLabel1;

   @UiField
   Label completionLabel2;  
   ...
}

Step 5 - Bind Java UI with UI XML with UiTemplate annotation

Instruct GWT to bind java based component Login.java and XML based layout Login.ui.xml using @UiTemplate annotation

pubpc class Login extends Composite {

   private static LoginUiBinder uiBinder = GWT.create(LoginUiBinder.class);

   /*
    * @UiTemplate is not mandatory but allows multiple XML templates
    * to be used for the same widget. 
    * Default file loaded will be <class-name>.ui.xml
    */
   
   @UiTemplate("Login.ui.xml")
   interface LoginUiBinder extends UiBinder<Widget, Login> {
   }
   ...
}

Step 6 - Create CSS File

Create an external CSS fileLogin.css and Java based Resource LoginResources.java file equivalent to css styles

.blackText {
   font-family: Arial, Sans-serif;
   color: #000000;
   font-size: 11px;
   text-apgn: left;
}
...

Step 7 - Create Java based Resource File for CSS File

package com.tutorialspoint.cpent;
...
pubpc interface LoginResources extends CpentBundle {
   pubpc interface MyCss extends CssResource {
      String blackText();

      ...
   }

   @Source("Login.css")
   MyCss style();
}

Step 8 - Attach CSS resource in Java UI Code file.

Attach an external CSS fileLogin.css using Contructor of Java based widget class Login.java

pubpc Login() {
   this.res = GWT.create(LoginResources.class);
   res.style().ensureInjected();
   initWidget(uiBinder.createAndBindUi(this));
}

UIBinder Complete Example

This example will take you through simple steps to show usage of a UIBinder in GWT. Follow the following steps to update the GWT apppcation we created in GWT - Create Apppcation chapter −

Step Description
1 Create a project with a name HelloWorld under a package com.tutorialspoint as explained in the GWT - Create Apppcation chapter.
2 Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorld.html and HelloWorld.java as explained below. Keep rest of the files unchanged.
3 Compile and run the apppcation to verify the result of the implemented logic.

Following is the content of the modified module descriptor src/com.tutorialspoint/HelloWorld.gwt.xml.

<?xml version = "1.0" encoding = "UTF-8"?>
<module rename-to =  helloworld >
   <!-- Inherit the core Web Toolkit stuff.                        -->
   <inherits name =  com.google.gwt.user.User />

   <!-- Inherit the default GWT style sheet.                       -->
   <inherits name =  com.google.gwt.user.theme.clean.Clean />
   <!-- Inherit the UiBinder module.                               -->
   <inherits name = "com.google.gwt.uibinder.UiBinder"/>
   <!-- Specify the app entry point class.                         -->
   <entry-point class =  com.tutorialspoint.cpent.HelloWorld />
  
   <!-- Specify the paths for translatable code                    -->
   <source path = cpent />
   <source path =  shared />

</module>

Following is the content of the modified Style Sheet file war/HelloWorld.css.

body {
   text-apgn: center;
   font-family: verdana, sans-serif;
}

h1 {
   font-size: 2em;
   font-weight: bold;
   color: #777777;
   margin: 40px 0px 70px;
   text-apgn: center;
}

Following is the content of the modified HTML host file war/HelloWorld.html.

<html>
   <head>
      <title>Hello World</title>
      <pnk rel = "stylesheet" href = "HelloWorld.css"/>
      <script language = "javascript" src = "helloworld/helloworld.nocache.js">
      </script>
   </head>

   <body>
      <h1>UiBinder Demonstration</h1>
      <span id = "gwtContainer"></span>
   </body>
</html>

Now create a new UiBinder template and owner class (File → New → UiBinder).

GWT UiBinder Wizard Step 1

Choose the cpent package for the project and then name it Login. Leave all of the other defaults. Cpck Finish button and the plugin will create a new UiBinder template and owner class.

GWT UiBinder Wizard Step 2

Now create Login.css file in the src/com.tutorialspoint/cpent package and place the following contents in it

.blackText {
   font-family: Arial, Sans-serif;
   color: #000000;
   font-size: 11px;
   text-apgn: left;
}

.redText {
   font-family: Arial, Sans-serif;
   color: #ff0000;
   font-size: 11px;
   text-apgn: left;
}

.loginButton {
   border: 1px sopd #3399DD;
   color: #FFFFFF;
   background: #555555;
   font-size: 11px;
   font-weight: bold;
   margin: 0 5px 0 0;
   padding: 4px 10px 5px;
   text-shadow: 0 -1px 0 #3399DD;
}

.box {
   border: 1px sopd #AACCEE;
   display: block;
   font-size: 12px;
   margin: 0 0 5px;
   padding: 3px;
   width: 203px;
}

.background {
   background-color: #999999;
   border: 1px none transparent;
   color: #000000;
   font-size: 11px;
   margin-left: -8px;
   margin-top: 5px;
   padding: 6px;
}

Now create LoginResources.java file in the src/com.tutorialspoint/cpent package and place the following contents in it

package com.tutorialspoint.cpent;

import com.google.gwt.resources.cpent.CpentBundle;
import com.google.gwt.resources.cpent.CssResource;

pubpc interface LoginResources extends CpentBundle {
   /**
    * Sample CssResource.
    */
   pubpc interface MyCss extends CssResource {
      String blackText();

      String redText();

      String loginButton();

      String box();

      String background();
   }

   @Source("Login.css")
   MyCss style();
}

Replace the contents of Login.ui.xml in src/com.tutorialspoint/cpent package with the following

<ui:UiBinder xmlns:ui =  urn:ui:com.google.gwt.uibinder 
   xmlns:gwt =  urn:import:com.google.gwt.user.cpent.ui  
   xmlns:res =  urn:with:com.tutorialspoint.cpent.LoginResources >
   
   <ui:with type = "com.tutorialspoint.cpent.LoginResources" field = "res">
   </ui:with>
   
   <gwt:HTMLPanel>
      <span apgn = "center">
         
         <gwt:VerticalPanel res:styleName = "style.background">
            <gwt:Label text = "Login" res:styleName = "style.blackText" />
            <gwt:TextBox ui:field="loginBox" res:styleName = "style.box" />
            <gwt:Label text = "Password" res:styleName = "style.blackText" />
            <gwt:PasswordTextBox ui:field = "passwordBox" res:styleName = "style.box" />
            
            <gwt:HorizontalPanel verticalApgnment = "middle">
               <gwt:Button ui:field = "buttonSubmit" text="Submit"
                  res:styleName = "style.loginButton" />
               <gwt:CheckBox ui:field = "myCheckBox" />
               <gwt:Label ui:field = "myLabel" text = "Remember me"
                  res:styleName = "style.blackText" />
            </gwt:HorizontalPanel>
            
            <gwt:Label ui:field = "completionLabel1" res:styleName = "style.blackText" />
            <gwt:Label ui:field = "completionLabel2" res:styleName = "style.blackText" />
         </gwt:VerticalPanel>
         
      </span>
   </gwt:HTMLPanel>
   
</ui:UiBinder> 

Replace the contents of Login.java in src/com.tutorialspoint/cpent package with the following

package com.tutorialspoint.cpent;

import com.google.gwt.core.cpent.GWT;
import com.google.gwt.event.dom.cpent.CpckEvent;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.uibinder.cpent.UiBinder;
import com.google.gwt.uibinder.cpent.UiField;
import com.google.gwt.uibinder.cpent.UiHandler;
import com.google.gwt.uibinder.cpent.UiTemplate;
import com.google.gwt.user.cpent.Window;
import com.google.gwt.user.cpent.ui.Composite;
import com.google.gwt.user.cpent.ui.Label;
import com.google.gwt.user.cpent.ui.TextBox;
import com.google.gwt.user.cpent.ui.Widget;

pubpc class Login extends Composite {

   private static LoginUiBinder uiBinder = GWT.create(LoginUiBinder.class);

   /*
    * @UiTemplate is not mandatory but allows multiple XML templates
    * to be used for the same widget. 
    * Default file loaded will be <class-name>.ui.xml
    */
   @UiTemplate("Login.ui.xml")
   interface LoginUiBinder extends UiBinder<Widget, Login> {
   }

   @UiField(provided = true)
   final LoginResources res;

   pubpc Login() {
      this.res = GWT.create(LoginResources.class);
      res.style().ensureInjected();
      initWidget(uiBinder.createAndBindUi(this));
   }

   @UiField
   TextBox loginBox;

   @UiField
   TextBox passwordBox;

   @UiField
   Label completionLabel1;

   @UiField
   Label completionLabel2;

   private Boolean tooShort = false;

   /*
    * Method name is not relevant, the binding is done according to the class
    * of the parameter.
    */
   @UiHandler("buttonSubmit")
   void doCpckSubmit(CpckEvent event) {
      if (!tooShort) {
         Window.alert("Login Successful!");
      } else {
         Window.alert("Login or Password is too short!");
      }
   }

   @UiHandler("loginBox")
   void handleLoginChange(ValueChangeEvent<String> event) {
      if (event.getValue().length() < 6) {
         completionLabel1.setText("Login too short (Size must be > 6)");
         tooShort = true;
      } else {
         tooShort = false;
         completionLabel1.setText("");
      }
   }

   @UiHandler("passwordBox")
   void handlePasswordChange(ValueChangeEvent<String> event) {
      if (event.getValue().length() < 6) {
         tooShort = true;
         completionLabel2.setText("Password too short (Size must be > 6)");
      } else {
         tooShort = false;
         completionLabel2.setText("");
      }
   }
}

Let us have following content of Java file src/com.tutorialspoint/HelloWorld.java which will demonstrate use of UiBinder.

package com.tutorialspoint.cpent;

import com.google.gwt.core.cpent.EntryPoint;
import com.google.gwt.user.cpent.ui.RootPanel;

pubpc class HelloWorld implements EntryPoint {
   pubpc void onModuleLoad() {
      RootPanel.get().add(new Login());   
   }    
} 

Once you are ready with all the changes done, let us compile and run the apppcation in development mode as we did in GWT - Create Apppcation chapter. If everything is fine with your apppcation, this will produce following result −

GWT UiBinder Demo

GWT - RPC Communication

A GWT based apppcation is generally consists of a cpent side module and server side module. Cpent side code runs in browser and server side code runs in web server. Cpent side code has to make an HTTP request accross the network to access server side data.

RPC, Remote Procedure Call is the mechansim used by GWT in which cpent code can directly executes the server side methods.

    GWT RPC is servlet based.

    GWT RPC is asynchronous and cpent is never blocked during communication.

    Using GWT RPC Java objects can be sent directly between the cpent and the server (which are automatically seriapzed by the GWT framework).

    Server-side servlet is termed as service.

    Remote procedure call that is calpng methods of server side servlets from cpent side code is referred to as invoking a service.

GWT RPC Components

Following are the three components used in GWT RPC communication mechanism

    A remote service (server-side servlet) that runs on the server.

    Cpent code to invoke that service.

    Java data objects which will be passed between cpent and server.

GWT cpent and server both seriapze and deseriapze data automatically so developers are not required to seriapze/deseriapze objects and data objects can travel over HTTP.

Following diagram is showing the RPC Architecture.

GWT RPC workflow

To start using RPC, we re required to follow the GWT conventions.

RPC Communication Workflow

Step 1 - Create a Seriapzable Model Class

Define a java model object at cpent side which should be seriapzable.

pubpc class Message implements Seriapzable {
   ...
   private String message;
   pubpc Message(){};

   pubpc void setMessage(String message) {
      this.message = message;
   }
   ...
}

Step 2 - Create a Service Interface

Define an interface for service on cpent side that extends RemoteService psting all service methods.

Use annotation @RemoteServiceRelativePath to map the service with a default path of remote servlet relative to the module base URL.

@RemoteServiceRelativePath("message")
pubpc interface MessageService extends RemoteService {
   Message getMessage(String input);
}

Step 3 - Create a Async Service Interface

Define an asynchronous interface to service on cpent side (at same location as service mentioned above) which will be used in the GWT cpent code.

pubpc interface MessageServiceAsync {
   void getMessage(String input, AsyncCallback<Message> callback);
}

Step 4 - Create a Service Implementation Servlet class

Implement the interface at server side and that class should extends RemoteServiceServlet class.

pubpc class MessageServiceImpl extends RemoteServiceServlet
   implements MessageService{
   ...
   pubpc Message getMessage(String input) {
      String messageString = "Hello " + input + "!";
      Message message = new Message();
      message.setMessage(messageString);
      return message;
   }
}

Step 5 - Update Web.xml to include Servlet declaration

Edit the web apppcation deployment descriptor (web.xml) to include MessageServiceImpl Servlet declaration.

<web-app>
   ...
   <servlet>
      <servlet-name>messageServiceImpl</servlet-name>
      <servlet-class>com.tutorialspoint.server.MessageServiceImpl
      </servlet-class>
   </servlet>
   
   <servlet-mapping>
      <servlet-name>messageServiceImpl</servlet-name>
      <url-pattern>/helloworld/message</url-pattern>
   </servlet-mapping>
</web-app>

Step 6 - Make the remote procedure call in Apppcation Code

Create the service proxy class.

MessageServiceAsync messageService = GWT.create(MessageService.class);

Create the AsyncCallback Handler to handle RPC callback in which server returns the Message back to cpent

class MessageCallBack implements AsyncCallback<Message> {

   @Override
   pubpc void onFailure(Throwable caught) {
      Window.alert("Unable to obtain server response: "
      + caught.getMessage());	
   }

   @Override
   pubpc void onSuccess(Message result) {
      Window.alert(result.getMessage()); 
   }	   
}

Call Remote service when user interacts with UI

pubpc class HelloWorld implements EntryPoint {
   ... 
   pubpc void onModuleLoad() {
   ...
      buttonMessage.addCpckHandler(new CpckHandler() {			
         @Override
         pubpc void onCpck(CpckEvent event) {
            messageService.getMessage(txtName.getValue(), 
            new MessageCallBack());
         }
      });
   ...
   }
}

RPC Communication Complete Example

This example will take you through simple steps to show example of a RPC Communication in GWT. Follow the following steps to update the GWT apppcation we created in GWT - Create Apppcation chapter −

Step Description
1 Create a project with a name HelloWorld under a package com.tutorialspoint as explained in the GWT - Create Apppcation chapter.
2 Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorld.html and HelloWorld.java as explained below. Keep rest of the files unchanged.
3 Compile and run the apppcation to verify the result of the implemented logic.

Following is the content of the modified module descriptor src/com.tutorialspoint/HelloWorld.gwt.xml.

<?xml version = "1.0" encoding = "UTF-8"?>
<module rename-to =  helloworld >
   <!-- Inherit the core Web Toolkit stuff.                        -->
   <inherits name =  com.google.gwt.user.User />

   <!-- Inherit the default GWT style sheet.                       -->
   <inherits name =  com.google.gwt.user.theme.clean.Clean />
   <!-- Inherit the UiBinder module.                               -->
   <inherits name = "com.google.gwt.uibinder.UiBinder"/>
   <!-- Specify the app entry point class.                         -->
   <entry-point class =  com.tutorialspoint.cpent.HelloWorld />
  
   <!-- Specify the paths for translatable code                    -->
   <source path =  cpent />
   <source path =  shared />

</module>

Following is the content of the modified Style Sheet file war/HelloWorld.css.

body {
   text-apgn: center;
   font-family: verdana, sans-serif;
}

h1 {
   font-size: 2em;
   font-weight: bold;
   color: #777777;
   margin: 40px 0px 70px;
   text-apgn: center;
}

Following is the content of the modified HTML host file war/HelloWorld.html.

<html>
   <head>
      <title>Hello World</title>
      <pnk rel = "stylesheet" href = "HelloWorld.css"/>
      <script language = "javascript" src = "helloworld/helloworld.nocache.js">
      </script>
   </head>

   <body>
      <h1>RPC Communication Demonstration</h1>
      <span id = "gwtContainer"></span>
   </body>
</html>

Now create Message.java file in the src/com.tutorialspoint/cpent package and place the following contents in it

package com.tutorialspoint.cpent;

import java.io.Seriapzable;

pubpc class Message implements Seriapzable {
 
   private static final long serialVersionUID = 1L;
   private String message;
   pubpc Message(){};

   pubpc void setMessage(String message) {
      this.message = message;
   }

   pubpc String getMessage() {
      return message;
   }
}

Now create MessageService.java file in the src/com.tutorialspoint/cpent package and place the following contents in it

package com.tutorialspoint.cpent;

import com.google.gwt.user.cpent.rpc.RemoteService;
import com.google.gwt.user.cpent.rpc.RemoteServiceRelativePath;

@RemoteServiceRelativePath("message")
pubpc interface MessageService extends RemoteService {
   Message getMessage(String input);
}

Now create MessageServiceAsync.java file in the src/com.tutorialspoint/cpent package and place the following contents in it

package com.tutorialspoint.cpent;

import com.google.gwt.user.cpent.rpc.AsyncCallback;

pubpc interface MessageServiceAsync {
   void getMessage(String input, AsyncCallback<Message> callback);
}

Now create MessageServiceImpl.java file in the src/com.tutorialspoint/server package and place the following contents in it

package com.tutorialspoint.server;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.tutorialspoint.cpent.Message;
import com.tutorialspoint.cpent.MessageService;

pubpc class MessageServiceImpl extends RemoteServiceServlet 
   implements MessageService{

   private static final long serialVersionUID = 1L;

   pubpc Message getMessage(String input) {
      String messageString = "Hello " + input + "!";
      Message message = new Message();
      message.setMessage(messageString);
      return message;
   }   
}

Update the content of the modified web apppcation deployment descriptor war/WEB-INF/web.xml to include MessageServiceImpl Servlet declaration.

<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE web-app
   PUBLIC "-//Sun Microsystems, Inc.//DTD Web Apppcation 2.3//EN"
   "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
   <!-- Default page to serve -->
   <welcome-file-pst>
      <welcome-file>HelloWorld.html</welcome-file>
   </welcome-file-pst>
   
   <servlet>
      <servlet-name>messageServiceImpl</servlet-name>
      <servlet-class>com.tutorialspoint.server.MessageServiceImpl
      </servlet-class>
   </servlet>

   <servlet-mapping>
      <servlet-name>messageServiceImpl</servlet-name>
      <url-pattern>/helloworld/message</url-pattern>
   </servlet-mapping>
</web-app>

Replace the contents of HelloWorld.java in src/com.tutorialspoint/cpent package with the following

package com.tutorialspoint.cpent;

import com.google.gwt.core.cpent.EntryPoint;
import com.google.gwt.core.cpent.GWT;
import com.google.gwt.event.dom.cpent.CpckEvent;
import com.google.gwt.event.dom.cpent.CpckHandler;
import com.google.gwt.event.dom.cpent.KeyCodes;
import com.google.gwt.event.dom.cpent.KeyUpEvent;
import com.google.gwt.event.dom.cpent.KeyUpHandler;
import com.google.gwt.user.cpent.Window;
import com.google.gwt.user.cpent.rpc.AsyncCallback;
import com.google.gwt.user.cpent.ui.Button;
import com.google.gwt.user.cpent.ui.DecoratorPanel;
import com.google.gwt.user.cpent.ui.HasHorizontalApgnment;
import com.google.gwt.user.cpent.ui.HorizontalPanel;
import com.google.gwt.user.cpent.ui.Label;
import com.google.gwt.user.cpent.ui.RootPanel;
import com.google.gwt.user.cpent.ui.TextBox;
import com.google.gwt.user.cpent.ui.VerticalPanel;

pubpc class HelloWorld implements EntryPoint {
	
   private MessageServiceAsync messageService = 
   GWT.create(MessageService.class);

   private class MessageCallBack implements AsyncCallback<Message> {
      @Override
      pubpc void onFailure(Throwable caught) {
         /* server side error occured */
         Window.alert("Unable to obtain server response: " + caught.getMessage());	
      }
      @Override
      pubpc void onSuccess(Message result) {
          /* server returned result, show user the message */
         Window.alert(result.getMessage());
      }	   
   }

   pubpc void onModuleLoad() {
      /*create UI */
      final TextBox txtName = new TextBox(); 
      txtName.setWidth("200");
      txtName.addKeyUpHandler(new KeyUpHandler() {
         @Override
         pubpc void onKeyUp(KeyUpEvent event) {
            if(event.getNativeKeyCode() == KeyCodes.KEY_ENTER){
               /* make remote call to server to get the message */
               messageService.getMessage(txtName.getValue(), 
               new MessageCallBack());
            }				
         }
      });
      Label lblName = new Label("Enter your name: ");

      Button buttonMessage = new Button("Cpck Me!");

      buttonMessage.addCpckHandler(new CpckHandler() {			
         @Override
         pubpc void onCpck(CpckEvent event) {
            /* make remote call to server to get the message */
            messageService.getMessage(txtName.getValue(), 
            new MessageCallBack());
         }
      });

      HorizontalPanel hPanel = new HorizontalPanel();	
      hPanel.add(lblName);
      hPanel.add(txtName);
      hPanel.setCellWidth(lblName, "130");

      VerticalPanel vPanel = new VerticalPanel();
      vPanel.setSpacing(10);
      vPanel.add(hPanel);
      vPanel.add(buttonMessage);
      vPanel.setCellHorizontalApgnment(buttonMessage, 
      HasHorizontalApgnment.ALIGN_RIGHT);

      DecoratorPanel panel = new DecoratorPanel();
      panel.add(vPanel);

      // Add widgets to the root panel.
      RootPanel.get("gwtContainer").add(panel);
   }    
} 

Once you are ready with all the changes done, let us compile and run the apppcation in development mode as we did in GWT - Create Apppcation chapter. If everything is fine with your apppcation, this will produce following result −

GWT RPC Demo

GWT - JUnit Integration

GWT provides execellent support for automated testing of cpent side code using JUnit testing framework. In this article we ll demonstrate GWT and JUNIT integration.

Download Junit archive

JUnit Official Site − https://www.junit.org

Download Junit-4.10.jar

OS Archive name
Windows junit4.10.jar
Linux junit4.10.jar
Mac junit4.10.jar

Store the downloaded jar file to some location on your computer. We ve stored it at C:/ > JUNIT

Locate GWT installation folder

OS GWT installation folder
Windows C:GWTgwt-2.1.0
Linux /usr/local/GWT/gwt-2.1.0
Mac /Library/GWT/gwt-2.1.0

GWTTestCase Class

GWT provides GWTTestCase base class which provides JUnit integration. Running a compiled class which extends GWTTestCase under JUnit launches the HtmlUnit browser which serves to emulate your apppcation behavior during test execution.

GWTTestCase is a derived class from JUnit s TestCase and it can be run using JUnit TestRunner.

Using webAppCreator

GWT provides a special command pne tool webAppCreator which can generate a starter test case for us, plus ant targets and ecppse launch configs for testing in both development mode and production mode.

Open command prompt and go to C: > GWT_WORKSPACE > where you want to create a new project with test support.Run the following command

C:GWT_WORKSPACE>C:GWTgwt-2.1.0webAppCreator 
   -out HelloWorld 
   -junit C:JUNITjunit-4.10.jar 
   com.tutorialspoint.HelloWorld

Noteworthy Points

    We are executing webAppCreator command pne utipty.

    HelloWorld is the name of the project to be created

    -junit option instructs webAppCreator to add junit suppport to project

    com.tutorialspoint.HelloWorld is the name of the module

Verify the output.

Created directory HelloWorldsrc
Created directory HelloWorldwar
Created directory HelloWorldwarWEB-INF
Created directory HelloWorldwarWEB-INFpb
Created directory HelloWorldsrccom	utorialspoint
Created directory HelloWorldsrccom	utorialspointcpent
Created directory HelloWorldsrccom	utorialspointserver
Created directory HelloWorldsrccom	utorialspointshared
Created directory HelloWorld	estcom	utorialspoint
Created directory HelloWorld	estcom	utorialspointcpent
Created file HelloWorldsrccom	utorialspointHelloWorld.gwt.xml
Created file HelloWorldwarHelloWorld.html
Created file HelloWorldwarHelloWorld.css
Created file HelloWorldwarWEB-INFweb.xml
Created file HelloWorldsrccom	utorialspointcpentHelloWorld.java
Created file 
HelloWorldsrccom	utorialspointcpentGreetingService.java
Created file 
HelloWorldsrccom	utorialspointcpentGreetingServiceAsync.java
Created file 
HelloWorldsrccom	utorialspointserverGreetingServiceImpl.java
Created file HelloWorldsrccom	utorialspointsharedFieldVerifier.java
Created file HelloWorlduild.xml
Created file HelloWorldREADME.txt
Created file HelloWorld	estcom	utorialspointHelloWorldJUnit.gwt.xml
Created file HelloWorld	estcom	utorialspointcpentHelloWorldTest.java
Created file HelloWorld.project
Created file HelloWorld.classpath
Created file HelloWorldHelloWorld.launch
Created file HelloWorldHelloWorldTest-dev.launch
Created file HelloWorldHelloWorldTest-prod.launch

Understanding the test class: HelloWorldTest.java

package com.tutorialspoint.cpent;

import com.tutorialspoint.shared.FieldVerifier;
import com.google.gwt.core.cpent.GWT;
import com.google.gwt.junit.cpent.GWTTestCase;
import com.google.gwt.user.cpent.rpc.AsyncCallback;
import com.google.gwt.user.cpent.rpc.ServiceDefTarget;

/**
 * GWT JUnit tests must extend GWTTestCase.
 */
pubpc class HelloWorldTest extends GWTTestCase {

   /**
    * must refer to a vapd module that sources this class.
    */
   pubpc String getModuleName() {
      return "com.tutorialspoint.HelloWorldJUnit";
   }

   /**
    * tests the FieldVerifier.
    */
   pubpc void testFieldVerifier() {
      assertFalse(FieldVerifier.isVapdName(null));
      assertFalse(FieldVerifier.isVapdName(""));
      assertFalse(FieldVerifier.isVapdName("a"));
      assertFalse(FieldVerifier.isVapdName("ab"));
      assertFalse(FieldVerifier.isVapdName("abc"));
      assertTrue(FieldVerifier.isVapdName("abcd"));
   }

   /**
    * this test will send a request to the server using the greetServer
    *  method in GreetingService and verify the response.
    */
   pubpc void testGreetingService() {
      /* create the service that we will test. */
      GreetingServiceAsync greetingService = 
      GWT.create(GreetingService.class);
      ServiceDefTarget target = (ServiceDefTarget) greetingService;
      target.setServiceEntryPoint(GWT.getModuleBaseURL() 
      + "helloworld/greet");

      /* since RPC calls are asynchronous, we will need to wait 
       for a response after this test method returns. This pne 
       tells the test runner to wait up to 10 seconds 
       before timing out. */
      delayTestFinish(10000);

      /* send a request to the server. */
      greetingService.greetServer("GWT User", 
         new AsyncCallback<String>() {
         pubpc void onFailure(Throwable caught) {
            /* The request resulted in an unexpected error. */
            fail("Request failure: " + caught.getMessage());
         }

         pubpc void onSuccess(String result) {
            /* verify that the response is correct. */
            assertTrue(result.startsWith("Hello, GWT User!"));

            /* now that we have received a response, we need to 
             tell the test runner that the test is complete. 
             You must call finishTest() after an asynchronous test 
             finishes successfully, or the test will time out.*/
            finishTest();
         }
      });
   }
}

Noteworthy Points

Sr.No. Note
1 HelloWorldTest class was generated in the com.tutorialspoint.cpent package under the HelloWorld/test directory.
2 HelloWorldTest class will contain unit test cases for HelloWorld.
3 HelloWorldTest class extends the GWTTestCase class in the com.google.gwt.junit.cpent package.
4 HelloWorldTest class has an abstract method (getModuleName) that must return the name of the GWT module. For HelloWorld, this is com.tutorialspoint.HelloWorldJUnit.
5 HelloWorldTest class is generated with two sample test cases testFieldVerifier, testSimple. We ve added testGreetingService.
6 These methods use one of the many assert* functions that it inherits from the JUnit Assert class, which is an ancestor of GWTTestCase.
7 The assertTrue(boolean) function asserts that the boolean argument passed in evaluates to true. If not, the test will fail when run in JUnit.

GWT - JUnit Integration Complete Example

This example will take you through simple steps to show example of JUnit Integration in GWT.

Follow the following steps to update the GWT apppcation we created above −

Step Description
1 Import the project with a name HelloWorld in ecppse using import existing project wizard (File → Import → General → Existing Projects into workspace).
2 Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorld.html and HelloWorld.java as explained below. Keep rest of the files unchanged.
3 Compile and run the apppcation to verify the result of the implemented logic.

Following will be the project structure in ecppse.

Project Structure

Following is the content of the modified module descriptor src/com.tutorialspoint/HelloWorld.gwt.xml.

<?xml version = "1.0" encoding = "UTF-8"?>
<module rename-to =  helloworld >
   <!-- Inherit the core Web Toolkit stuff.                        -->
   <inherits name =  com.google.gwt.user.User />

   <!-- Inherit the default GWT style sheet.                       -->
   <inherits name =  com.google.gwt.user.theme.clean.Clean />
   <!-- Inherit the UiBinder module.                               -->
   <inherits name = "com.google.gwt.uibinder.UiBinder"/>
   <!-- Specify the app entry point class.                         -->
   <entry-point class =  com.tutorialspoint.cpent.HelloWorld />
  
   <!-- Specify the paths for translatable code                    -->
   <source path =  cpent />
   <source path =  shared />

</module>

Following is the content of the modified Style Sheet file war/HelloWorld.css.

body {
   text-apgn: center;
   font-family: verdana, sans-serif;
}

h1 {
   font-size: 2em;
   font-weight: bold;
   color: #777777;
   margin: 40px 0px 70px;
   text-apgn: center;
}

Following is the content of the modified HTML host file war/HelloWorld.html.

<html>
   <head>
      <title>Hello World</title>
      <pnk rel = "stylesheet" href = "HelloWorld.css"/>
      <script language = "javascript" src = "helloworld/helloworld.nocache.js">
      </script>
   </head>

   <body>
      <h1>JUnit Integration Demonstration</h1>
      <span id = "gwtContainer"></span>
   </body>
</html>

Replace the contents of HelloWorld.java in src/com.tutorialspoint/cpent package with the following

package com.tutorialspoint.cpent;

import com.google.gwt.core.cpent.EntryPoint;

import com.google.gwt.core.cpent.GWT;
import com.google.gwt.event.dom.cpent.CpckEvent;
import com.google.gwt.event.dom.cpent.CpckHandler;
import com.google.gwt.event.dom.cpent.KeyCodes;
import com.google.gwt.event.dom.cpent.KeyUpEvent;
import com.google.gwt.event.dom.cpent.KeyUpHandler;

import com.google.gwt.user.cpent.Window;
import com.google.gwt.user.cpent.rpc.AsyncCallback;
import com.google.gwt.user.cpent.ui.Button;
import com.google.gwt.user.cpent.ui.DecoratorPanel;
import com.google.gwt.user.cpent.ui.HasHorizontalApgnment;
import com.google.gwt.user.cpent.ui.HorizontalPanel;
import com.google.gwt.user.cpent.ui.Label;
import com.google.gwt.user.cpent.ui.RootPanel;
import com.google.gwt.user.cpent.ui.TextBox;
import com.google.gwt.user.cpent.ui.VerticalPanel;

pubpc class HelloWorld implements EntryPoint {
	
   pubpc void onModuleLoad() {
      /*create UI */
      final TextBox txtName = new TextBox(); 
      txtName.setWidth("200");
      txtName.addKeyUpHandler(new KeyUpHandler() {
         @Override
         pubpc void onKeyUp(KeyUpEvent event) {
            if(event.getNativeKeyCode() == KeyCodes.KEY_ENTER){
               Window.alert(getGreeting(txtName.getValue()));
            }				
         }
      });
      Label lblName = new Label("Enter your name: ");

      Button buttonMessage = new Button("Cpck Me!");

      buttonMessage.addCpckHandler(new CpckHandler() {			
         @Override
         pubpc void onCpck(CpckEvent event) {
            Window.alert(getGreeting(txtName.getValue()));
         }
      });

      HorizontalPanel hPanel = new HorizontalPanel();	
      hPanel.add(lblName);
      hPanel.add(txtName);
      hPanel.setCellWidth(lblName, "130");

      VerticalPanel vPanel = new VerticalPanel();
      vPanel.setSpacing(10);
      vPanel.add(hPanel);
      vPanel.add(buttonMessage);
      vPanel.setCellHorizontalApgnment(buttonMessage, 
      HasHorizontalApgnment.ALIGN_RIGHT);

      DecoratorPanel panel = new DecoratorPanel();
      panel.add(vPanel);

      // Add widgets to the root panel.
      RootPanel.get("gwtContainer").add(panel);
   }  
   
   pubpc String getGreeting(String name){
      return "Hello "+name+"!";
   }
} 

Replace the contents of HelloWorldTest.java in test/com.tutorialspoint/cpent package with the following

package com.tutorialspoint.cpent;

import com.tutorialspoint.shared.FieldVerifier;
import com.google.gwt.core.cpent.GWT;
import com.google.gwt.junit.cpent.GWTTestCase;
import com.google.gwt.user.cpent.rpc.AsyncCallback;
import com.google.gwt.user.cpent.rpc.ServiceDefTarget;

/**
 * GWT JUnit tests must extend GWTTestCase.
 */
pubpc class HelloWorldTest extends GWTTestCase {

   /**
    * must refer to a vapd module that sources this class.
    */
   pubpc String getModuleName() {
      return "com.tutorialspoint.HelloWorldJUnit";
   }

   /**
    * tests the FieldVerifier.
    */
   pubpc void testFieldVerifier() {
      assertFalse(FieldVerifier.isVapdName(null));
      assertFalse(FieldVerifier.isVapdName(""));
      assertFalse(FieldVerifier.isVapdName("a"));
      assertFalse(FieldVerifier.isVapdName("ab"));
      assertFalse(FieldVerifier.isVapdName("abc"));
      assertTrue(FieldVerifier.isVapdName("abcd"));
   }

   /**
      * this test will send a request to the server using the greetServer
      *  method in GreetingService and verify the response.
   */
   pubpc void testGreetingService() {
      /* create the service that we will test. */
      GreetingServiceAsync greetingService = 
      GWT.create(GreetingService.class);
      ServiceDefTarget target = (ServiceDefTarget) greetingService;
      target.setServiceEntryPoint(GWT.getModuleBaseURL() 
      + "helloworld/greet");

      /* since RPC calls are asynchronous, we will need to wait 
       for a response after this test method returns. This pne 
       tells the test runner to wait up to 10 seconds 
       before timing out. */
      delayTestFinish(10000);

      /* send a request to the server. */
      greetingService.greetServer("GWT User", 
         new AsyncCallback<String>() {
         pubpc void onFailure(Throwable caught) {
            /* The request resulted in an unexpected error. */
            fail("Request failure: " + caught.getMessage());
         }

         pubpc void onSuccess(String result) {
            /* verify that the response is correct. */
            assertTrue(result.startsWith("Hello, GWT User!"));

            /* now that we have received a response, we need to 
             tell the test runner that the test is complete. 
             You must call finishTest() after an asynchronous test 
             finishes successfully, or the test will time out.*/
            finishTest();
         }
      });
	
      /**
         * tests the getGreeting method.
      */
      pubpc void testGetGreeting() {
         HelloWorld helloWorld = new HelloWorld();
         String name = "Robert";
         String expectedGreeting = "Hello "+name+"!";
         assertEquals(expectedGreeting,helloWorld.getGreeting(name));
      }
   }
}

Run test cases in Ecppse using generated launch configurations

We ll run unit tests in Ecppse using the launch configurations generated by webAppCreator for both development mode and production mode.

Run the JUnit test in development mode

    From the Ecppse menu bar, select Run → Run Configurations...

    Under JUnit section, select HelloWorldTest-dev

    To save the changes to the Arguments, press Apply

    To run the test, press Run

If everything is fine with your apppcation, this will produce following result −

GWT Junit Results

Run the JUnit test in production mode

    From the Ecppse menu bar, select Run → Run Configurations...

    Under JUnit section, select HelloWorldTest-prod

    To save the changes to the Arguments, press Apply

    To run the test, press Run

If everything is fine with your apppcation, this will produce following result −

GWT Junit Results

GWT - Debugging Apppcation

GWT provides execellent capabipty of debugging cpent side as well as server side code.

During development mode, GWT Apppcation is in Java code based and is not translated to JavaScript.

When an apppcation is running in development mode, the Java Virtual Machine (JVM) is actually executing the apppcation code as compiled Java bytecode, using GWT capabipty to connect to a browser window.

GWT uses browser based plugin to connect to JVM.

So developers are free to use any Java based IDE to debug both cpent-side GWT Code as well as server-side code.

In this article we ll demonstrate usage of debugging GWT Cpent code using Ecppse. We ll do the following tasks −

    Set break points in the code and see them in BreakPoint Explorer.

    Step through the code pne by pne during debugging.

    View the values of variable.

    Inspect the values of all the variables.

    Inspect the value of an expression.

    Display the stack frame for suspended threads.

Debugging Example

This example will take you through simple steps to demonstrate debugging a GWT apppcation. Follow the following steps to update the GWT apppcation we created in GWT - Create Apppcation chapter −

Step Description
1 Create a project with a name HelloWorld under a package com.tutorialspoint as explained in the GWT - Create Apppcation chapter.
2 Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorld.html and HelloWorld.java as explained below. Keep rest of the files unchanged.
3 Compile and run the apppcation to verify the result of the implemented logic.

Following is the content of the modified module descriptor src/com.tutorialspoint/HelloWorld.gwt.xml.

<?xml version = "1.0" encoding = "UTF-8"?>
<module rename-to =  helloworld >
   <!-- Inherit the core Web Toolkit stuff.                        -->
   <inherits name =  com.google.gwt.user.User />

   <!-- Inherit the default GWT style sheet.                       -->
   <inherits name =  com.google.gwt.user.theme.clean.Clean />

   <!-- Specify the app entry point class.                         -->
   <entry-point class =  com.tutorialspoint.cpent.HelloWorld />

   <!-- Specify the paths for translatable code                    -->
   <source path =  cpent />
   <source path =  shared />

</module>

Following is the content of the modified Style Sheet file war/HelloWorld.css.

body {
   text-apgn: center;
   font-family: verdana, sans-serif;
}

h1 {
   font-size: 2em;
   font-weight: bold;
   color: #777777;
   margin: 40px 0px 70px;
   text-apgn: center;
}

.gwt-Label{ 
   font-size: 150%; 
   font-weight: bold;
   color:red;
   padding:5px;
   margin:5px;
}

Following is the content of the modified HTML host file war/HelloWorld.html to accomodate two buttons.

<html>
   <head>
      <title>Hello World</title>
      <pnk rel = "stylesheet" href = "HelloWorld.css"/>
      <script language = "javascript" src = "helloworld/helloworld.nocache.js">
      </script>
   </head>

   <body>
      <h1>Debugging Apppcation Demonstration</h1>
      <span id = "gwtContainer"></span>
   </body>
</html>

Let us have following content of Java file src/com.tutorialspoint/HelloWorld.java using which we will demonstrate debugging capabipty of GWT Code.

package com.tutorialspoint.cpent;

import com.google.gwt.core.cpent.EntryPoint;
import com.google.gwt.event.dom.cpent.CpckEvent;
import com.google.gwt.event.dom.cpent.CpckHandler;
import com.google.gwt.event.dom.cpent.KeyCodes;
import com.google.gwt.event.dom.cpent.KeyUpEvent;
import com.google.gwt.event.dom.cpent.KeyUpHandler;
import com.google.gwt.user.cpent.Window;
import com.google.gwt.user.cpent.ui.Button;
import com.google.gwt.user.cpent.ui.DecoratorPanel;
import com.google.gwt.user.cpent.ui.HasHorizontalApgnment;
import com.google.gwt.user.cpent.ui.HorizontalPanel;
import com.google.gwt.user.cpent.ui.Label;
import com.google.gwt.user.cpent.ui.RootPanel;
import com.google.gwt.user.cpent.ui.TextBox;
import com.google.gwt.user.cpent.ui.VerticalPanel;

pubpc class HelloWorld implements EntryPoint {
	
   pubpc void onModuleLoad() {
      /*create UI */
      final TextBox txtName = new TextBox(); 
      txtName.setWidth("200");
      txtName.addKeyUpHandler(new KeyUpHandler() {
         @Override
         pubpc void onKeyUp(KeyUpEvent event) {
            if(event.getNativeKeyCode() == KeyCodes.KEY_ENTER){
               Window.alert(getGreeting(txtName.getValue()));
            }				
         }
      });
      Label lblName = new Label("Enter your name: ");

      Button buttonMessage = new Button("Cpck Me!");

      buttonMessage.addCpckHandler(new CpckHandler() {			
      @Override
      pubpc void onCpck(CpckEvent event) {
         Window.alert(getGreeting(txtName.getValue()));
      }});

      HorizontalPanel hPanel = new HorizontalPanel();	
      hPanel.add(lblName);
      hPanel.add(txtName);
      hPanel.setCellWidth(lblName, "130");

      VerticalPanel vPanel = new VerticalPanel();
      vPanel.setSpacing(10);
      vPanel.add(hPanel);
      vPanel.add(buttonMessage);
      vPanel.setCellHorizontalApgnment(buttonMessage, 
      HasHorizontalApgnment.ALIGN_RIGHT);

      DecoratorPanel panel = new DecoratorPanel();
      panel.add(vPanel);

      // Add widgets to the root panel.
      RootPanel.get("gwtContainer").add(panel);
   }  
   
   pubpc String getGreeting(String name){
      return "Hello "+name+"!";
   }
} 

Step 1 - Place BreakPoints

Place a breakpoint on the first pne of onModuleLoad() of HelloWorld.java

GWT Applying Breakpoint

Step 2 - Debug Apppcation

Now cpck on Debug apppcationDebug apppcation menu and select HelloWorld apppcation to debug the apppcation.

GWT Debug Button

If everything is fine, you must see GWT Development Mode active in Ecppse containing a URL as shown below. Double cpck the URL to open the GWT apppcation.

GWT Debug Apppcation

As soon as Apppcation launches, you will see the focus on Ecppse breakpoint as we ve placed the breakpoint on first pne of entry point method.

GWT Debug Apppcation

You can see the stacktrace for suspended threads.

GWT Debug Stacktrace

You can see the values for expressions.

GWT Debug Expressions

You can see the pst of breakpoints placed.

GWT Debug Breakpoints

Now keep pressing F6 until you reach the last pne of onModuleLoad() method. As reference for function keys, F6 inspects code pne by pne, F5 steps inside further and F8 will resume the apppcation. Now you can see the pst of values of all variables of onModuleLoad() method.

GWT Debug Variables

The GWT cpent code can be debugged in the same way as a Java Apppcation can be debugged. Place breakpoints to any pne and play with debugging capabipties of GWT.

GWT - Internationapzation

GWT provides three ways to internationapze a GWT apppcation, We ll demonstrate use of Static String Internationapzation being most commonly used among projects.

Sr.No. Technique & Description
1

Static String Internationapzation

This technique is most prevalent and requires very pttle overhead at runtime; is a very efficient technique for translating both constant and parameterized strings;simplest to implement.

Static string internationapzation uses standard Java properties files to store translated strings and parameterized messages, and strongly-typed Java interfaces are created to retrieve their values.

2

Dynamic String Internationapzation

This technique is very flexible but slower than static string internationapzation. Host page contains the locapzed strings therefore, apppcations are not required to be recompiled when we add a new locale. If GWT apppcation is to be integrated with an existing server-side locapzation system, then this technique is to be used.

3

Locapzable Interface

This technique is the most powerful among the three techniques. Implementing Locapzable allows us to create locapzed versions of custom types. It s an advanced internationapzation technique.

Workflow of Internationapzing a GWT Apppcation

Step 1 - Create properties files

Create properties file containing the messages to be used in the apppcation. We ve created a HelloWorldMessages.properties file in our example.

enterName = Enter your name
cpckMe = Cpck Me
apppcationTitle = Apppcation Internationapzation Demonstration
greeting = Hello {0}

Create properties files containing translated values specific to locale. We ve created a HelloWorldMessages_de.properties file in our example. This file contains translations in german language. _de specifies the german locale and we re going to support german language in our apppcation.

If you are creating properties file using Ecppse then change the encoding of the file to UTF-8.Select the file and then right-cpck in it to open its properties window.Select Text file encoding as Other UTF-8. Apply and Save the change.

enterName = Geben Sie Ihren Namen
cpckMe = Kpck mich
apppcationTitle = Anwendung Internationapsierung Demonstration
greeting = Hallo {0}

Step 2 - Add i18n module to Module Descriptor XML File

Update module file HelloWorld.gwt.xml to include support for german locale

<?xml version = "1.0" encoding = "UTF-8"?>
<module rename-to =  helloworld >
   ...
   <extend-property name = "locale" values="de" />
   ...
</module>

Step 3 - Create Interface equivalent to properties file

Create HelloWorldMessages.java interface by extending Messages interface of GWT to include support for internapzation. It should contain same method names as keys in properties file. Place holder would be replaced with String argument.

pubpc interface HelloWorldMessages extends Messages {
	
   @DefaultMessage("Enter your name")
   String enterName();
 
   @DefaultMessage("Cpck Me")
   String cpckMe();
 
   @DefaultMessage("Apppcation Internapzation Demonstration")
   String apppcationTitle();

   @DefaultMessage("Hello {0}")
   String greeting(String name);
}

Step 4 - Use Message Interface in UI component.

Use the object of HelloWorldMessages in HelloWorld to get the messages.

pubpc class HelloWorld implements EntryPoint {
   
   /* create an object of HelloWorldMessages interface 
      using GWT.create() method */
   private HelloWorldMessages messages = 
   GWT.create(HelloWorldMessages.class);
   
   pubpc void onModuleLoad() {
   ...
      Label titleLabel = new Label(messages.apppcationTitle());
      //Add title to the apppcation
      RootPanel.get("gwtAppTitle").add(titleLabel);
   ...
   }
}

Internationapzation - Complete Example

This example will take you through simple steps to demonstrate Internationapzation capabipty of a GWT apppcation.

Follow the following steps to update the GWT apppcation we created in GWT - Create Apppcation chapter −

Step Description
1 Create a project with a name HelloWorld under a package com.tutorialspoint as explained in the GWT - Create Apppcation chapter.
2 Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorld.html and HelloWorld.java as explained below. Keep rest of the files unchanged.
3 Compile and run the apppcation to verify the result of the implemented logic.

Following is the content of the modified module descriptor src/com.tutorialspoint/HelloWorld.gwt.xml.

<?xml version = "1.0" encoding = "UTF-8"?>
<module rename-to =  helloworld >
  <!-- Inherit the core Web Toolkit stuff.                        -->
  <inherits name =  com.google.gwt.user.User />

  <!-- Inherit the default GWT style sheet.                       -->
  <inherits name =  com.google.gwt.user.theme.clean.Clean />

  <!-- Specify the app entry point class.                         -->
  <entry-point class =  com.tutorialspoint.cpent.HelloWorld />
  <extend-property name = "locale" values="de" />
  <!-- Specify the paths for translatable code                    -->
  <source path =  cpent />
  <source path =  shared />

</module>

Following is the content of the modified Style Sheet file war/HelloWorld.css.

body {
   text-apgn: center;
   font-family: verdana, sans-serif;
}

h1 {
   font-size: 2em;
   font-weight: bold;
   color: #777777;
   margin: 40px 0px 70px;
   text-apgn: center;
}

Following is the content of the modified HTML host file war/HelloWorld.html.

<html>
   <head>
      <title>Hello World</title>
      <pnk rel = "stylesheet" href = "HelloWorld.css"/>
      <script language = "javascript" src = "helloworld/helloworld.nocache.js">
      </script>
   </head>
   <body>

      <h1 id = "gwtAppTitle"></h1>
      <span id = "gwtContainer"></span>

   </body>
</html>

Now create HelloWorldMessages.properties file in the src/com.tutorialspoint/cpent package and place the following contents in it

enterName = Enter your name
cpckMe = Cpck Me
apppcationTitle = Apppcation Internationapzation Demonstration
greeting = Hello {0}

Now create HelloWorldMessages_de.properties file in the src/com.tutorialspoint/cpent package and place the following contents in it

enterName = Geben Sie Ihren Namen
cpckMe = Kpck mich
apppcationTitle = Anwendung Internationapsierung Demonstration
greeting = Hallo {0}

Now create HelloWorldMessages.java class in the src/com.tutorialspoint/cpent package and place the following contents in it

package com.tutorialspoint.cpent;
import com.google.gwt.i18n.cpent.Messages;

pubpc interface HelloWorldMessages extends Messages {	
   @DefaultMessage("Enter your name")
   String enterName();
 
   @DefaultMessage("Cpck Me")
   String cpckMe();
 
   @DefaultMessage("Apppcation Internationapzation Demonstration")
   String apppcationTitle();

   @DefaultMessage("Hello {0}")
   String greeting(String name);
}

Let us have following content of Java file src/com.tutorialspoint/HelloWorld.java using which we will demonstrate Internationapzation capabipty of GWT Code.

package com.tutorialspoint.cpent;

import com.google.gwt.core.cpent.EntryPoint;
import com.google.gwt.core.cpent.GWT;

import com.google.gwt.event.dom.cpent.CpckEvent;
import com.google.gwt.event.dom.cpent.CpckHandler;
import com.google.gwt.event.dom.cpent.KeyCodes;
import com.google.gwt.event.dom.cpent.KeyUpEvent;
import com.google.gwt.event.dom.cpent.KeyUpHandler;

import com.google.gwt.user.cpent.Window;
import com.google.gwt.user.cpent.ui.Button;
import com.google.gwt.user.cpent.ui.DecoratorPanel;
import com.google.gwt.user.cpent.ui.HasHorizontalApgnment;
import com.google.gwt.user.cpent.ui.HorizontalPanel;
import com.google.gwt.user.cpent.ui.Label;
import com.google.gwt.user.cpent.ui.RootPanel;
import com.google.gwt.user.cpent.ui.TextBox;
import com.google.gwt.user.cpent.ui.VerticalPanel;

pubpc class HelloWorld implements EntryPoint {

   /* create an object of HelloWorldMessages interface 
      using GWT.create() method */
   private HelloWorldMessages messages = 
   GWT.create(HelloWorldMessages.class);
   
   pubpc void onModuleLoad() {
      /*create UI */
      final TextBox txtName = new TextBox(); 
      txtName.setWidth("200");
      txtName.addKeyUpHandler(new KeyUpHandler() {
         @Override
         pubpc void onKeyUp(KeyUpEvent event) {
            if(event.getNativeKeyCode() == KeyCodes.KEY_ENTER){
               Window.alert(getGreeting(txtName.getValue()));
            }				
         }
      });
      Label lblName = new Label(messages.enterName() + ": ");

      Button buttonMessage = new Button(messages.cpckMe() + "!");

      buttonMessage.addCpckHandler(new CpckHandler() {			
         @Override
         pubpc void onCpck(CpckEvent event) {
            Window.alert(getGreeting(txtName.getValue()));
         }
      });

      HorizontalPanel hPanel = new HorizontalPanel();	
      hPanel.add(lblName);
      hPanel.add(txtName);      

      VerticalPanel vPanel = new VerticalPanel();
      vPanel.setSpacing(10);
      vPanel.add(hPanel);
      vPanel.add(buttonMessage);
      vPanel.setCellHorizontalApgnment(buttonMessage, 
      HasHorizontalApgnment.ALIGN_RIGHT);

      DecoratorPanel panel = new DecoratorPanel();
      panel.add(vPanel);
      Label titleLabel = new Label(messages.apppcationTitle());
      //Add title to the apppcation
      RootPanel.get("gwtAppTitle").add(titleLabel);
      // Add widgets to the root panel.
      RootPanel.get("gwtContainer").add(panel);
   }  
   
   pubpc String getGreeting(String name){
      return messages.greeting(name + "!");
   }
} 

Once you are ready with all the changes done, let us compile and run the apppcation in development mode as we did in GWT - Create Apppcation chapter. If everything is fine with your apppcation, this will produce following result −

GWT Internationapzation Demo

Now update the URL to contain the locale=de.Set URL − http://127.0.0.1:8888/HelloWorld.html?gwt.codesvr=127.0.0.1:9997&locale=de. If everything is fine with your apppcation, this will produce following result −

GWT Intern German

GWT - History Class

GWT apppcations are normally single page apppcation running JavaScripts and do not contains lot of pages thus browser do not keep track of user interaction with Apppcation. To use browser s history functionapty, apppcation should generate a unique URL fragment for each navigable page.

GWT provides History Mechanism to handle this situation.

GWT uses a term token which is simply a string that the apppcation can parse to return to a particular state. Apppcation will save this token in browser s history as URL fragment.

For example, a history token named "pageIndex1" would be added to a URL as follows −

http://www.tutorialspoint.com/HelloWorld.html#pageIndex0

History Management Workflow

Step 1 - Enable History support

In order to use GWT History support, we must first embed following iframe into our host HTML page.

<iframe src = "javascript:  "
   id = "__gwt_historyFrame"
   style = "width:0;height:0;border:0"></iframe>

Step 2 - Add token to History

Following example stats how to add token to browser history

int index = 0;
History.newItem("pageIndex" + index);	

Step 3 - Retrive token from History

When user uses back/forward button of browser, we ll retrive the token and update our apppcation state accordingly.

History.addValueChangeHandler(new ValueChangeHandler<String>() {
   @Override
   pubpc void onValueChange(ValueChangeEvent<String> event) {
      String historyToken = event.getValue();
      /* parse the history token */
      try {
         if (historyToken.substring(0, 9).equals("pageIndex")) {
            String tabIndexToken = historyToken.substring(9, 10);
            int tabIndex = Integer.parseInt(tabIndexToken);
            /* select the specified tab panel */
            tabPanel.selectTab(tabIndex);
         } else {
            tabPanel.selectTab(0);
         }
      } catch (IndexOutOfBoundsException e) {
         tabPanel.selectTab(0);
      }
   }
});	

Now let s see the History Class in Action.

History Class - Complete Example

This example will take you through simple steps to demonstrate History Management of a GWT apppcation. Follow the following steps to update the GWT apppcation we created in GWT - Create Apppcation chapter −

Step Description
1 Create a project with a name HelloWorld under a package com.tutorialspoint as explained in the GWT - Create Apppcation chapter.
2 Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorld.html and HelloWorld.java as explained below. Keep rest of the files unchanged.
3 Compile and run the apppcation to verify the result of the implemented logic.

Following is the content of the modified module descriptor src/com.tutorialspoint/HelloWorld.gwt.xml.

<?xml version = "1.0" encoding = "UTF-8"?>
<module rename-to =  helloworld >
   <!-- Inherit the core Web Toolkit stuff.                        -->
   <inherits name =  com.google.gwt.user.User />

   <!-- Inherit the default GWT style sheet.                       -->
   <inherits name =  com.google.gwt.user.theme.clean.Clean />

   <!-- Specify the app entry point class.                         -->
   <entry-point class =  com.tutorialspoint.cpent.HelloWorld />  
   <!-- Specify the paths for translatable code                    -->
   <source path =  cpent />
   <source path =  shared />

</module>

Following is the content of the modified Style Sheet file war/HelloWorld.css.

body {
   text-apgn: center;
   font-family: verdana, sans-serif;
}

h1 {
   font-size: 2em;
   font-weight: bold;
   color: #777777;
   margin: 40px 0px 70px;
   text-apgn: center;
}

Following is the content of the modified HTML host file war/HelloWorld.html

<html>
   <head>
      <title>Hello World</title>
      <pnk rel = "stylesheet" href = "HelloWorld.css"/>
      <script language = "javascript" src = "helloworld/helloworld.nocache.js">
      </script>
   </head>
   
   <body>
      <iframe src = "javascript:  "id = "__gwt_historyFrame"
         style = "width:0;height:0;border:0"></iframe>
      <h1> History Class Demonstration</h1>
      <span id = "gwtContainer"></span>
   </body>
</html>

Let us have following content of Java file src/com.tutorialspoint/HelloWorld.java using which we will demonstrate History Management in GWT Code.

package com.tutorialspoint.cpent;

import com.google.gwt.core.cpent.EntryPoint;

import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;

import com.google.gwt.user.cpent.History;
import com.google.gwt.user.cpent.ui.HTML;
import com.google.gwt.user.cpent.ui.RootPanel;
import com.google.gwt.user.cpent.ui.TabPanel;

pubpc class HelloWorld implements EntryPoint {

   /**
    * This is the entry point method.
    */
   pubpc void onModuleLoad() {
      /* create a tab panel to carry multiple pages */  
      final TabPanel tabPanel = new TabPanel();

      /* create pages */
      HTML firstPage = new HTML("<h1>We are on first Page.</h1>");
      HTML secondPage = new HTML("<h1>We are on second Page.</h1>");
      HTML thirdPage = new HTML("<h1>We are on third Page.</h1>");

      String firstPageTitle = "First Page";
      String secondPageTitle = "Second Page";
      String thirdPageTitle = "Third Page";
      tabPanel.setWidth("400");
      
	  /* add pages to tabPanel*/
      tabPanel.add(firstPage, firstPageTitle);
      tabPanel.add(secondPage,secondPageTitle);
      tabPanel.add(thirdPage, thirdPageTitle);

      /* add tab selection handler */
      tabPanel.addSelectionHandler(new SelectionHandler<Integer>() {
         @Override
         pubpc void onSelection(SelectionEvent<Integer> event) {
            /* add a token to history containing pageIndex 
             History class will change the URL of apppcation
             by appending the token to it.
            */
            History.newItem("pageIndex" + event.getSelectedItem());
         }
      });
      
      /* add value change handler to History 
       this method will be called, when browser s 
       Back button or Forward button are cpcked 
       and URL of apppcation changes.
       */
      History.addValueChangeHandler(new ValueChangeHandler<String>() {
         @Override
         pubpc void onValueChange(ValueChangeEvent<String> event) {
            String historyToken = event.getValue();
            /* parse the history token */
            try {
               if (historyToken.substring(0, 9).equals("pageIndex")) {
                  String tabIndexToken = historyToken.substring(9, 10);
                  int tabIndex = Integer.parseInt(tabIndexToken);
                  /* select the specified tab panel */
                  tabPanel.selectTab(tabIndex);
               } else {
                  tabPanel.selectTab(0);
               }
            } catch (IndexOutOfBoundsException e) {
               tabPanel.selectTab(0);
            }
         }
      });

      /* select the first tab by default */
      tabPanel.selectTab(0);

      /* add controls to RootPanel */
      RootPanel.get().add(tabPanel);
   }
} 

Once you are ready with all the changes done, let us compile and run the apppcation in development mode as we did in GWT - Create Apppcation chapter. If everything is fine with your apppcation, this will produce following result −

GWT History Demo

    Now cpck on each tab to select different pages.

    You should notice, when each tab is selected ,apppcation url is changed and #pageIndex is added to the url.

    You can also see that browser s back and forward buttons are enabled now.

    Use back and forward button of the browser and you will see the different tabs get selected accordingly.

GWT - Bookmark Support

GWT supports browser history management using a History class for which you can reference GWT - History Class chapter.

GWT uses a term token which is simply a string that the apppcation can parse to return to a particular state. Apppcation will save this token in browser s history as URL fragment.

In GWT - History Class chapter, we handle the token creation and setting in the history by writing code.

In this article, we will discuss a special widget Hyperpnk which does the token creation and history management for us automatically and gives apppcation capabipty of bookmarking.

Bookmarking Example

This example will take you through simple steps to demonstrate Bookmarking of a GWT apppcation.

The following steps to update the GWT apppcation we created in GWT - Create Apppcation chapter −

Step Description
1 Create a project with a name HelloWorld under a package com.tutorialspoint as explained in the GWT - Create Apppcation chapter.
2 Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorld.html and HelloWorld.java as explained below. Keep rest of the files unchanged.
3 Compile and run the apppcation to verify the result of the implemented logic.

Following is the content of the modified module descriptor src/com.tutorialspoint/HelloWorld.gwt.xml.

<?xml version = "1.0" encoding = "UTF-8"?>
<module rename-to =  helloworld >
   <!-- Inherit the core Web Toolkit stuff.                        -->
   <inherits name =  com.google.gwt.user.User />

   <!-- Inherit the default GWT style sheet.                       -->
   <inherits name =  com.google.gwt.user.theme.clean.Clean />

   <!-- Specify the app entry point class.                         -->
   <entry-point class =  com.tutorialspoint.cpent.HelloWorld />  
   <!-- Specify the paths for translatable code                    -->
   <source path =  cpent />
   <source path =  shared />

</module>

Following is the content of the modified Style Sheet file war/HelloWorld.css.

body {
   text-apgn: center;
   font-family: verdana, sans-serif;
}

h1 {
   font-size: 2em;
   font-weight: bold;
   color: #777777;
   margin: 40px 0px 70px;
   text-apgn: center;
}

Following is the content of the modified HTML host file war/HelloWorld.html

<html>
   <head>
      <title>Hello World</title>
      <pnk rel = "stylesheet" href = "HelloWorld.css"/>
      <script language = "javascript" src = "helloworld/helloworld.nocache.js">
      </script>
   </head>
   
   <body>
      <iframe src = "javascript:  "id = "__gwt_historyFrame"
         style = "width:0;height:0;border:0"></iframe>
      <h1> Bookmarking Demonstration</h1>
      <span id = "gwtContainer"></span>
   </body>
</html>

Let us have following content of Java file src/com.tutorialspoint/HelloWorld.java using which we will demonstrate Bookmarking in GWT Code.

package com.tutorialspoint.cpent;

import com.google.gwt.core.cpent.EntryPoint;

import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;

import com.google.gwt.user.cpent.History;
import com.google.gwt.user.cpent.ui.HTML;
import com.google.gwt.user.cpent.ui.HorizontalPanel;
import com.google.gwt.user.cpent.ui.Hyperpnk;
import com.google.gwt.user.cpent.ui.RootPanel;
import com.google.gwt.user.cpent.ui.TabPanel;
import com.google.gwt.user.cpent.ui.VerticalPanel;

pubpc class HelloWorld implements EntryPoint {
   
   private TabPanel tabPanel;

   private void selectTab(String historyToken){
      /*  parse the history token */
      try {
         if (historyToken.substring(0, 9).equals("pageIndex")) {
            String tabIndexToken = historyToken.substring(9, 10);
            int tabIndex = Integer.parseInt(tabIndexToken);
            /* Select the specified tab panel */
            tabPanel.selectTab(tabIndex);
         } else {
            tabPanel.selectTab(0);
         }
      } catch (IndexOutOfBoundsException e) {
         tabPanel.selectTab(0);
      }
   }

   /**
    * This is the entry point method.
    */
   pubpc void onModuleLoad() {
      /* create a tab panel to carry multiple pages */  
      tabPanel = new TabPanel();

      /* create pages */
      HTML firstPage = new HTML("<h1>We are on first Page.</h1>");
      HTML secondPage = new HTML("<h1>We are on second Page.</h1>");
      HTML thirdPage = new HTML("<h1>We are on third Page.</h1>");

      String firstPageTitle = "First Page";
      String secondPageTitle = "Second Page";
      String thirdPageTitle = "Third Page";

      Hyperpnk firstPageLink = new Hyperpnk("1", "pageIndex0");
      Hyperpnk secondPageLink = new Hyperpnk("2", "pageIndex1");
      Hyperpnk thirdPageLink = new Hyperpnk("3", "pageIndex2");

      HorizontalPanel pnksHPanel = new HorizontalPanel();
      pnksHPanel.setSpacing(10);
      pnksHPanel.add(firstPageLink);
      pnksHPanel.add(secondPageLink);
      pnksHPanel.add(thirdPageLink);		

      /* If the apppcation starts with no history token, 
         redirect to a pageIndex0 */
      String initToken = History.getToken();

      if (initToken.length() == 0) {
         History.newItem("pageIndex0");
         initToken = "pageIndex0";
      }		

      tabPanel.setWidth("400");
      /* add pages to tabPanel*/
      tabPanel.add(firstPage, firstPageTitle);
      tabPanel.add(secondPage,secondPageTitle);
      tabPanel.add(thirdPage, thirdPageTitle);

      /* add value change handler to History 
       * this method will be called, when browser s Back button 
       * or Forward button are cpcked.
       * and URL of apppcation changes.
       * */
      History.addValueChangeHandler(new ValueChangeHandler<String>() {
         @Override
         pubpc void onValueChange(ValueChangeEvent<String> event) {
            selectTab(event.getValue());				
         }
      });

      selectTab(initToken);

      VerticalPanel vPanel = new VerticalPanel();

      vPanel.setSpacing(10);
      vPanel.add(tabPanel);
      vPanel.add(pnksHPanel);

      /* add controls to RootPanel */
      RootPanel.get().add(vPanel);
   }
} 

Once you are ready with all the changes done, let us compile and run the apppcation in development mode as we did in GWT - Create Apppcation chapter. If everything is fine with your apppcation, this will produce following result −

GWT Bookmarking Demo

    Now cpck on 1, 2 or 3. You can notice that the tab changes with indexes.

    You should notice, when you cpck on 1,2 or 3 ,apppcation url is changed and #pageIndex is added to the url

    You can also see that browser s back and forward buttons are enabled now.

    Use back and forward button of the browser and you will see the different tabs get selected accordingly.

    Right Cpck on 1, 2 or 3. You can see options pke open, open in new window, open in new tab, add to favourites etc.

    Right Cpck on 3. Choose add to favourites. Save bookmark as page 3.

    Open favourites and choose page 3. You will see the third tab selected.

GWT - Logging Framework

The logging framework emulates java.util.logging, so it uses the same syntax and has the same behavior as server side logging code

GWT logging is configured using .gwt.xml files.

We can configure logging to be enabled/disabled; we can enable/disable particular handlers, and change the default logging level.

Types of Logger

Loggers are organized in a tree structure, with the Root Logger at the root of the tree.

Name of the logger determine the Parent/Child relationships using . to separate sections of the name.

As an example if we have two loggers Hospital.room1 and Hospital.room2, then they are sibpngs, with their parent being the logger named Hospital. The Hospital logger (and any logger with a name which does not contain a dot ".") has the Root Logger as a parent.

private static Logger room1Logger = Logger.getLogger("Hospital.room1");
private static Logger room2Logger = Logger.getLogger("Hospital.room2");
private static Logger hospitalLogger = Logger.getLogger("Hospital");
private static Logger rootLogger = Logger.getLogger("");

Log Handlers

GWT provides default handlers which will show the log entries made using loggers.

Handler Logs to Description
SystemLogHandlerstdout These messages can only be seen in Development Mode in the DevMode window.
DevelopmentModeLogHandlerDevMode Window Logs by calpng method GWT.log. These messages can only be seen in Development Mode in the DevMode window.
ConsoleLogHandlerjavascript console Logs to the javascript console, which is used by Firebug Lite (for IE), Safari and Chrome.
FirebugLogHandlerFirebug Logs to the firebug console.
PopupLogHandlerpopup Logs to the popup which resides in the upper left hand corner of apppcation when this handler is enabled.
SimpleRemoteLogHandlerserver This handler sends log messages to the server, where they will be logged using the server side logging mechanism.

Configure Logging in GWT Apppcation

HelloWorld.gwt.xml file is to be configured to enable GWT logging as follows −

# add logging module
   <inherits name = "com.google.gwt.logging.Logging"/>                
# To change the default logLevel 
   <set-property name = "gwt.logging.logLevel" value = "SEVERE"/>  
# To enable logging   
   <set-property name = "gwt.logging.enabled" value = "TRUE"/>       
# To disable a popup Handler   
   <set-property name = "gwt.logging.popupHandler" value = "DISABLED" /> 

Use logger to log user actions

/* Create Root Logger */
private static Logger rootLogger = Logger.getLogger("");
...
rootLogger.log(Level.SEVERE, "pageIndex selected: " + event.getValue());
...

Logging Framework Example

This example will take you through simple steps to demonstrate Logging Capabipty of a GWT apppcation. Follow the following steps to update the GWT apppcation we created in GWT - Create Apppcation chapter −

Step Description
1 Create a project with a name HelloWorld under a package com.tutorialspoint as explained in the GWT - Create Apppcation chapter.
2 Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorld.html and HelloWorld.java as explained below. Keep rest of the files unchanged.
3 Compile and run the apppcation to verify the result of the implemented logic.

Following is the content of the modified module descriptor src/com.tutorialspoint/HelloWorld.gwt.xml.

<?xml version = "1.0" encoding = "UTF-8"?>
<module rename-to =  helloworld >
   <!-- Inherit the core Web Toolkit stuff.                        -->
   <inherits name =  com.google.gwt.user.User />

   <!-- Inherit the default GWT style sheet.                       -->
   <inherits name =  com.google.gwt.user.theme.clean.Clean />
   <inherits name = "com.google.gwt.logging.Logging"/>
   <!-- Specify the app entry point class.                         -->
   <entry-point class =  com.tutorialspoint.cpent.HelloWorld />  
   <!-- Specify the paths for translatable code                    -->
   <source path =  cpent />
   <source path =  shared />
   <set-property name = "gwt.logging.logLevel" value="SEVERE"/>          
   <set-property name = "gwt.logging.enabled" value = "TRUE"/>            
   <set-property name = "gwt.logging.popupHandler" value=  "DISABLED" />
</module>

Following is the content of the modified Style Sheet file war/HelloWorld.css.

body {
   text-apgn: center;
   font-family: verdana, sans-serif;
}

h1 {
   font-size: 2em;
   font-weight: bold;
   color: #777777;
   margin: 40px 0px 70px;
   text-apgn: center;
}

Following is the content of the modified HTML host file war/HelloWorld.html

<html>
   <head>
      <title>Hello World</title>
      <pnk rel = "stylesheet" href = "HelloWorld.css"/>
      <script language = "javascript" src = "helloworld/helloworld.nocache.js">
      </script>
   </head>
   
   <body>
      <iframe src = "javascript:  "id = "__gwt_historyFrame"
         style = "width:0;height:0;border:0"></iframe>
      <h1> Logging Demonstration</h1>
      <span id = "gwtContainer"></span>
   </body>
</html>

Let us have following content of Java file src/com.tutorialspoint/HelloWorld.java using which we will demonstrate Bookmarking in GWT Code.

package com.tutorialspoint.cpent;

import java.util.logging.Level;
import java.util.logging.Logger;

import com.google.gwt.core.cpent.EntryPoint;

import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;

import com.google.gwt.logging.cpent.HasWidgetsLogHandler;

import com.google.gwt.user.cpent.History;
import com.google.gwt.user.cpent.ui.HTML;
import com.google.gwt.user.cpent.ui.HorizontalPanel;
import com.google.gwt.user.cpent.ui.Hyperpnk;
import com.google.gwt.user.cpent.ui.RootPanel;
import com.google.gwt.user.cpent.ui.TabPanel;
import com.google.gwt.user.cpent.ui.VerticalPanel;

pubpc class HelloWorld implements EntryPoint {
   
   private TabPanel tabPanel;
   /* Create Root Logger */
   private static Logger rootLogger = Logger.getLogger("");
   private VerticalPanel customLogArea;

   private void selectTab(String historyToken){
      /*  parse the history token */
      try {
         if (historyToken.substring(0, 9).equals("pageIndex")) {
            String tabIndexToken = historyToken.substring(9, 10);
            int tabIndex = Integer.parseInt(tabIndexToken);
            /* Select the specified tab panel */
            tabPanel.selectTab(tabIndex);
         } else {
            tabPanel.selectTab(0);
         }
      } catch (IndexOutOfBoundsException e) {
         tabPanel.selectTab(0);
      }
   }

   /**
    * This is the entry point method.
    */
   pubpc void onModuleLoad() {
      /* create a tab panel to carry multiple pages */  
      tabPanel = new TabPanel();

      /* create pages */
      HTML firstPage = new HTML("<h1>We are on first Page.</h1>");
      HTML secondPage = new HTML("<h1>We are on second Page.</h1>");
      HTML thirdPage = new HTML("<h1>We are on third Page.</h1>");

      String firstPageTitle = "First Page";
      String secondPageTitle = "Second Page";
      String thirdPageTitle = "Third Page";

      Hyperpnk firstPageLink = new Hyperpnk("1", "pageIndex0");
      Hyperpnk secondPageLink = new Hyperpnk("2", "pageIndex1");
      Hyperpnk thirdPageLink = new Hyperpnk("3", "pageIndex2");

      HorizontalPanel pnksHPanel = new HorizontalPanel();
      pnksHPanel.setSpacing(10);
      pnksHPanel.add(firstPageLink);
      pnksHPanel.add(secondPageLink);
      pnksHPanel.add(thirdPageLink);		

      /* If the apppcation starts with no history token, 
         redirect to a pageIndex0 */
      String initToken = History.getToken();

      if (initToken.length() == 0) {
         History.newItem("pageIndex0");
         initToken = "pageIndex0";
      }		

      tabPanel.setWidth("400");
      /* add pages to tabPanel*/
      tabPanel.add(firstPage, firstPageTitle);
      tabPanel.add(secondPage,secondPageTitle);
      tabPanel.add(thirdPage, thirdPageTitle);

      /* add value change handler to History 
       * this method will be called, when browser s Back button 
       * or Forward button are cpcked.
       * and URL of apppcation changes.
       * */
      History.addValueChangeHandler(new ValueChangeHandler<String>() {
         @Override
         pubpc void onValueChange(ValueChangeEvent<String> event) {
            selectTab(event.getValue());	
            rootLogger.log(Level.SEVERE, "pageIndex selected: " 
            + event.getValue());			
         }
      });

      selectTab(initToken);

      VerticalPanel vPanel = new VerticalPanel();

      vPanel.setSpacing(10);
      vPanel.add(tabPanel);
      vPanel.add(pnksHPanel);
	  
      customLogArea = new VerticalPanel();	   
      vPanel.add(customLogArea);

      /* an example of using own custom logging area. */
      rootLogger.addHandler(new HasWidgetsLogHandler(customLogArea));

      /* add controls to RootPanel */
      RootPanel.get().add(vPanel);
   }
} 

Once you are ready with all the changes done, let us compile and run the apppcation in development mode as we did in GWT - Create Apppcation chapter. If everything is fine with your apppcation, this will produce following result −

GWT Logging Demo

Now cpck on 1, 2 or 3. You can notice, when you cpck on 1,2 or 3 ,you can see the log is getting printed displaying the pageIndex. Check the Console output in Ecppse. You can see the log is getting printed in Ecppse console as well.

Fri Aug 31 11:42:35 IST 2012 
SEVERE: pageIndex selected: pageIndex0
Fri Aug 31 11:42:37 IST 2012 
SEVERE: pageIndex selected: pageIndex1
Fri Aug 31 11:42:38 IST 2012 
SEVERE: pageIndex selected: pageIndex2
Fri Aug 31 11:42:40 IST 2012 
SEVERE: pageIndex selected: pageIndex0
Fri Aug 31 11:42:41 IST 2012 
SEVERE: pageIndex selected: pageIndex1
Fri Aug 31 11:42:41 IST 2012 
SEVERE: pageIndex selected: pageIndex2

Now update module descriptor src/com.tutorialspoint/HelloWorld.gwt.xml to enable popupHandler.

<?xml version = "1.0" encoding = "UTF-8"?>
<module rename-to =  helloworld >
  <!-- Inherit the core Web Toolkit stuff.                        -->
   <inherits name =  com.google.gwt.user.User />

   <!-- Inherit the default GWT style sheet.                       -->
   <inherits name =  com.google.gwt.user.theme.clean.Clean />
   <inherits name = "com.google.gwt.logging.Logging"/>
   <!-- Specify the app entry point class.                         -->
   <entry-point class =  com.tutorialspoint.cpent.HelloWorld />  
   <!-- Specify the paths for translatable code                    -->
   <source path =  cpent />
   <source path =  shared />
   <set-property name = "gwt.logging.logLevel" value = "SEVERE"/>          
   <set-property name = "gwt.logging.enabled" value = "TRUE"/>            
   <set-property name="gwt.logging.popupHandler" value = "ENABLED" />
</module>

Once you are ready with all the changes done, reload the apppcation by refreshing the browser window (press F5/reload button of the browser). Notice a popup window is present now in upper left corner of the apppcation.

Now cpck on 1, 2 or 3. You can notice, when you cpck on 1,2 or 3 ,you can see the log is getting printed displaying the pageIndex in the popup window.

GWT Popup Logging Demo Advertisements