GWT

0
35

What is GWT?

  • Google Web Toolkit (GWT) is a makement toolkit to generate RICH Internet Application(RIA).

  • GWT provides makeers option to write claynt aspect application in JAVA.

  • GWT compiles the code written in JAVA to JavaScript code.

  • Application written in GWT is combination-blineser compliant. GWT automatically generates javascript code suitable for every blineser.

  • GWT is open source, comppermitely free, and used simply by thougreat fine sands of makeers around the world. It is licensed below the Apache License version 2.0.

Overall, GWT is a framework to build big size and high performance web appliation while maintaining them as easy-to-maintain.

Why to use GWT?

  • Being Java based, you can use JAVA IDEs like Eclipse to make GWT applcation. Developers can use code auto-comppermite/reftake actionionoring/navigation/project management and all features of IDEs.

  • GWT provides compallowe debugging cappossible. Developers can debug the claynt aspect application simply as an Java Application.

  • GWT provides easy integration with Jdevice and Maven.

  • Again being Java based, GWT has a low find outing curve for Java Developers.

  • GWT generates optimized javascript code, produces blineser's specific javascript code simply by self.

  • GWT provides Widgets library provides many kind of kind of of tasks requireddish coloured-coloureddish coloured in an application.

  • GWT is extensible and custom widget can be generated to cater to application needs.

On top of everyslimg, GWT applications can operate on all major blinesers and smart phones including Android and iOS based phones/tabpermit is.

Disadvantages of GWT

Though GWT comes with lots of plus points but extake action same time we should conaspectr the following points:

  • Not indexable : Web pages generated simply by GWT would not be indexed simply by oceanrch engines because these applications are generated dynamically.

  • Not degradable: If your own application user disables Javascript then user will simply see the basic page and noslimg more.

  • Not styleer's friendly: GWT is not suitable for web styleers who prefer uperform basic HTML with placeholders for inserting dynamic content at later point in time.

The GWT Components

The GWT framework can be divided into following 3 major parts:

  • GWT Java to JavaScript compiler : This is the many kind of kind of iminterfaceant part of GWT which generates it a powerful tool for building RIAs. The GWT compiler is used to translate all the application code written in Java into JavaScript.

  • JRE Emulation library : Google Web Toolkit includes a library that emulates a subset of the Java operatetime library. The list includes java.lang, java.lang.annotation, java.math, java.io, java.sql, java.util and java.util.logging

  • GWT UI building library : This part of GWT consists of many kind of kind of subparts which includes the take actionionual UI components, RPC supinterface, History management, and a lot more.

GWT furthermore provides a GWT Hosted Web Blineser which permit is you operate and execute your own GWT applications in hosted mode, where your own code operates as Java in the Java Virtual Machine without presently there compiling to JavaScript.

GWT – Environment Setup

This tutorial will guide you on how to prepare a makement environment to start your own work with GWT Framework. This tutorial will furthermore tevery you how to setup JDK, Tomcat and Eclipse on your own machine before you setup GWT Framework:

System Requirement

GWT requires JDK 1.6 or higher so the very preliminary requirement is to have JDK instalbrought in your own 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 own environment to start with GWT application makement.

Step 1 – Verify Java installation on your own 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 out presently thereput for all the operating systems:

OS Generated Output
Windows java version "1.6.0_21"
Java(TM) SE Runtime Environment (build 1.6.0_21-b07)
Java HotSpot(TM) Claynt VM (build 17.0-b17, mixed mode, sharing)
Linux java version "1.6.0_21"
Java(TM) SE Runtime Environment (build 1.6.0_21-b07)
Java HotSpot(TM) Claynt VM (build 17.0-b17, mixed mode, sharing)
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 instalbrought then you can install the Java Softbattlee Development Kit (SDK) from Oracle's Java sit down downe: Java SE Downloads. You will find instructions for installing 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 immediateory 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 immediateory location where Java is withinstalbrought on your own machine. For example

OS Output
Windows Set the environment variable JAVA_HOME to C:Program FilesJavajdk1.6.0_21
Linux exinterface JAVA_HOME=/usr/local/java-current
Mac exinterface JAVA_HOME=/Library/Java/Home

Append Java compiler location to System Path.

OS Output
Windows Append the string ;%JAVA_HOME%bin to the end of the system variable, Path.
Linux exinterface PATH=$PATH:$JAVA_HOME/bin/
Mac not requireddish coloured-coloureddish coloured

Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, compile and operate a basic program to confirm that the IDE belowstands where you instalbrought Java, otherwise do proper setup as given document of the IDE.

Step 3 – Setup Eclipse IDE

All the examples in this particular particular tutorial have been written uperform Eclipse IDE. So I would suggest you should have lacheck version of Eclipse instalbrought on your own machine based on your own operating system.

To install Eclipse IDE, download the lacheck Eclipse binaries from /index.php?s=httpwwweclipseorgdownloads. Once you downloaded the installation, unpack the binary distribution into a convenient location. For example in C:eclipse on windows, or /usr/local/eclipse on Linux/Unix and finally set PATH variable appropriately.

Eclipse can be started simply by executing the following commands on windows machine, or you can simply double click on eclipse.exe

 %C:eclipseeclipse.exe

Eclipse can be started simply by executing the following commands on Unix (Solaris, Linux, etc.) machine:

$/usr/local/eclipse/eclipse

After a successful startup, if everyslimg is great then it should display following result:

Eclipse Home page

Step 4: Install GWT SDK & Plugin for Eclipse

Follow the instructions given at the link Plugin for Eclipse (incl. SDKs) to install GWT SDK & Plugin for Eclipse version instalbrought on your own machine.

After a successful setup for the GWT plugin, if everyslimg is great then it should display following screen with google icon marked with reddish coloured-coloureddish coloured rectangle:

Eclipse with Google

Step 5: Setup Apache Tomcat:

You can download the lacheck version of Tomcat from /index.php?s=httptomcatapacheorg. 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 simply by executing the following commands on windows machine, or you can simply double click on startup.bat

 %CATALINA_HOME%binstartup.bat
 
 or
 
 C:apache-tomcat-6.0.33binstartup.bat

Tomcat can be started simply by executing the following commands on Unix (Solaris, Linux, etc.) machine:

$CATALINA_HOME/bin/startup.sh
 
or
 
/usr/local/apache-tomcat-6.0.33/bin/startup.sh

After a successful startup, the default web applications included with Tomcat will be available simply by visit down downing http://localhost:8080/. If everyslimg is great then it should display following result:

Tomcat Home page

Further information about presently there configuring and operatening Tomcat can be found in the documentation included here, as well as on the Tomcat web sit down downe: http://tomcat.apache.org

Tomcat can be endped simply by executing the following commands on windows machine:

%CATALINA_HOME%binshutdown

or

C:apache-tomcat-5.5.29binshutdown

Tomcat can be endped simply 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 – Applications

Before we start with creating take actionionual HelloWorld application uperform GWT, permit us see extake actionionly extake actionly what are the take actionionual parts of a GWT application. A GWT application consists of following four iminterfaceant parts out presently there of which final part is optional but preliminary 3 parts are mandatory:

  • Module descriptors

  • Public resources

  • Claynt-aspect code

  • Server-aspect code

Sample locations of various parts of a typical gwt application HelloWord will be as shown below:

Name Location
Project main HelloWorld/
Module descriptor src/com/tutorialspoint/HelloWorld.gwt.xml
Public resources src/com/tutorialspoint/battle/
Claynt-aspect code src/com/tutorialspoint/claynt/
Server-aspect 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 application. A module descriptor file extension is *.gwt.xml, where * is the name of the application and this particular particular file should reaspect in the project's main. Following will be a default module descriptor HelloWorld.gwt.xml for a HelloWorld application:

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

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

   <!-- specify the app enconsider point course.                         -->
   <enconsider-point course='com.tutorialspoint.claynt.HelloWorld'/>

   <!-- specify the routes for translatable code                    -->
   <source route='...'/>
   <source route='...'/>

   <!-- specify the routes for static files like html, css etc.     -->
   <public route='...'/>
   <public route='...'/>

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

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

Following is the short detail about presently there various parts used in module descriptor.

S.N. Nodes & Description
1 <module rename-to="helloworld">
This provides name of the application.
2 <inherit is name="logical-module-name" />This adds other gwt module in application simply like iminterface does in java applications. Any number of modules can be inherited in this particular particular manner.
3 <enconsider-point course="coursename" />This specifies the name of course which will start loading the GWT Application. Any number of enconsider-point coursees can be added and they are calbrought sequentially in the order in which they appear in the module file. So when the onModuleLoad() of your own preliminary enconsider point compenableees, the next enconsider point is calbrought immediately.
4 <source route="route" />This specifies the names of source folders which GWT compiler will oceanrch for source compilation.
5 <public route="route" />The public route is the place in your own project where static resources referenced simply by your own GWT module, such as CSS or images, are storeddish coloured-coloureddish coloured. The default public route is the public subimmediateory belowneath where the Module XML File is storeddish coloured-coloureddish coloured.
6 <script src="js-url" />Automatically injects the external JavaScript file located at the location specified simply by src.
7 <stylesheet src="css-url" />Automatically injects the external CSS file located at the location specified simply by src.

Public resources

These are all files referenced simply by your own GWT module, such as Host HTML page, CSS or images. The location of these resources can be configureddish coloured-coloureddish coloured uperform <public route="route" /> element in module configuration file. By default, it is the public subimmediateory belowneath where the Module XML File is storeddish coloured-coloureddish coloured.

When you compile your own application into JavaScript, all the files that can be found on your own public route are copied to the module's out presently thereput immediateory.

The many kind of kind of iminterfaceant public resource is host page which is used to invoke take actionionual GWT application. A typical HTML host page for an application may not include any kind of kind of visible HTML body content at all but it is always expected to include GWT application via a <script…/> tag as follows:

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

<h1>Hello World</h1>
<p>Welcome to preliminary GWT application</p>

</body>
</html>

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

body {
   text-align: centre;
   font-family: verdana, sans-serif;
}
h1 {
  font-size: 2em;
  font-weight: bold;
  colour: #777777;
  margin: 40px 0px 70px;
  text-align: centre;
}

Claynt-aspect code

This is the take actionionual Java code written implementing the business logic of the application and that the GWT compiler translates into JavaScript, which will alsotually operate inaspect the blineser. The location of these resources can be configureddish coloured-coloureddish coloured uperform <source route="route" /> element in module configuration file.

For example Enconsider Point code will be used as claynt aspect code and it is location will be specified uperform <source route="route" />. A module enconsider-point is any kind of kind of course that is bumignable to EnconsiderPoint and that can be constructed without presently there parameters. When a module is loaded, every enconsider point course is immediateiated and it is EnconsiderPoint.onModuleLoad() method gets calbrought. A sample HelloWorld Enconsider Point course will be as follows:

public course HelloWorld implements EnconsiderPoint {
   public void onModuleLoad() {
      Window.alert("Hello, World!");
   }
}

Server-aspect code

This is the server aspect part of your own application and it is very a lot optional. If you are not doing any kind of kind of backend procesperform with-in your own application then you do not need this particular particular part, but if presently there is a few procesperform requireddish coloured-coloureddish coloured at backend and your own claynt-aspect application intertake actionion with the server then you will have to make these components.

Next chapter will generate use of all the above mentioned concepts to generate HelloWorld application uperform Eclipse IDE.

GWT – Create Application

As power of GWT lays in Write in Java, Run in JavaScript, we'll be uperform Java IDE Eclipse to demonstrate our examples. Let's start with a basic HelloWorld application:

Step 1 – Create Project

The preliminary step is to generate a basic Web Application Project uperform Eclipse IDE. Launch project wizard uperform the option Google Icon Google Services and Development Tools > New Web Application Project…. Now name your own project as HelloWorld uperform the wizard window as follows:

Create GWT Project Wizard

Unselect Use Google App Engine because we're not uperform it in this particular particular project and maintain other default values (maintain Generate Sample project code option checked) as such and click Finish Button. Once your own project is generated successcompallowey, you will have following content in your own Project Explorer:

GWT Project Structure

Here is short description of all iminterfaceant folders:

Folder Location
src
  • Source code (java coursees) files.

  • Claynt folder containing the claynt-aspect specific java coursees responsible for claynt UI display.

  • Server folder containing the server-aspect java coursees responsible for server aspect procesperform.

  • Shareddish coloured-coloureddish coloured folder containing the java model course to transfer data from server to claynt and vice versa.

  • HelloWorld.gwt.xml, a module descriptor file requireddish coloured-coloureddish coloured for GWT compiler to compile the HelloWorld project.

check
  • Test code (java coursees) source files.

  • Claynt folder containing the java coursees responsible to check gwt claynt aspect code.

battle
  • This is the many kind of kind of iminterfaceant part, it represents the take actionionual deployable web application.

  • WEB-INF containing compibrought coursees, gwt libraries, servpermit libraries.

  • HelloWorld.css, project style sheet.

  • HelloWorld.html, hots HTML which will invoke GWT UI Application.

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

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

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

  <!-- Inherit the default GWT style sheet.  You can modify       -->
  <!-- the theme of your own GWT application simply by uncommenting          -->
  <!-- any kind of kind of one of the following ranges.                            -->
  <inherit is name='com.google.gwt.user.theme.thoroughly clean.Clean'/>
  <!-- <inherit is name='com.google.gwt.user.theme.chrome.Chrome'/> -->
  <!-- <inherit is name='com.google.gwt.user.theme.darkishish.Dark'/>     -->

  <!-- Other module inherit is                                      -->

  <!-- Specify the app enconsider point course.                         -->
  <enconsider-point course='com.tutorialspoint.claynt.HelloWorld'/>

  <!-- Specify the routes for translatable code                    -->
  <source route='claynt'/>
  <source route='shareddish coloured-coloureddish coloured'/>

</module>

Step 3 – Modify Style Sheet: HelloWorld.css

GWT plugin will generate a default Style Sheet file battle/HelloWorld.css. Let us modify this particular particular file to maintain our example at basicst level of belowstaning:

body {
   text-align: centre;
   font-family: verdana, sans-serif;
}
h1 {
  font-size: 2em;
  font-weight: bold;
  colour: #777777;
  margin: 40px 0px 70px;
  text-align: centre;
}

Step 4 – Modify Host File: HelloWorld.html

GWT plugin will generate a default HTML host file battle/HelloWorld.html. Let us modify this particular particular file to maintain our example at basicst level of belowstaning:

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

<h1>Hello World</h1>
<p>Welcome to preliminary GWT application</p>

</body>
</html>

You can generate more static files like HTML, CSS or images in the extake action same source immediateory or you can generate further sub-immediateories and move files in those sub-immediateories and configure those sub-immediateories in module descriptor of the application.

Step 5 – Modify Enconsider Point: HelloWorld.java

GWT plugin will generate a default Java file src/com.tutorialspoint/HelloWorld.java, which maintains an enconsider point for the application. Let us modify this particular particular file to display "Hello,World!":

package com.tutorialspoint.claynt;

iminterface com.google.gwt.core.claynt.EnconsiderPoint;
iminterface com.google.gwt.user.claynt.Window;

public course HelloWorld implements EnconsiderPoint {
   public void onModuleLoad() {
	   Window.alert("Hello, World!");
   }
}

You can generate more Java files in the extake action same source immediateory to degreat possibly enconsider points or to degreat helper rout presently thereines.

Step 6 – Compile Application

Once you are ready with all the modifys done, it is time to compile the project. Use the option Google Icon Google Services and Development Tools > GWT Compile Project… to launch GWT Compile dialogue package as shown below:

Compile GWT Project Wizard

Keep default values inttake actionion and click Compile button. If everyslimg goes great, you will see following out presently thereput in Eclipse console

Compiling module com.tutorialspoint.HelloWorld
   Compiling 6 permutations
      Compiling permutation 0...
      Compiling permutation 1...
      Compiling permutation 2...
      Compiling permutation 3...
      Compiling permutation 4...
      Compiling permutation 5...
   Compile of permutations succeeded
Lincalifornia california king into C:workspaceHelloWorldbattlehelloworld
   Link succeeded
   Compilation succeeded -- 33.029s

Step 6 – Run Application

Now click on Run applicationRun application menu and select HelloWorld application to operate the application.

GWT Run Button

If everyslimg is great, you must see GWT Development Mode take actionionive in Eclipse containing a URL as shown below. Double click the URL to open the GWT application.

GWT Run Application

Because you are operatening your own application in makement mode, so you will need to install GWT plugin for your own blineser. Simply follow the onscreen instructions to install the plugin. If you already have GWT plugin set for your own blineser, then you should be able to see the following out presently thereput:

GWT Application Result

Congratulations! you have implemented your own preliminary application uperform Google Web Toolkit (GWT).

GWT – Deploy Application

This tutorial will exbasic you how to generate an application battle file and how to deploy that in Apache Tomcat Websever main. If you belowstood this particular particular basic example then you will furthermore be able to deploy a complex GWT application following the extake action same steps.

Let us have worcalifornia california king Eclipse IDE asizey with GWT plug in place and follow the following steps to generate a GWT application:

Step Description
1 Create a project with a name HelloWorld below a package com.tutorialspoint as exbasiced in the GWT – Create Application chapter.
2 Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorld.html and HelloWorld.java as exbasiced below. Keep rest of the files unmodifyd.
3 Compile and operate the application to generate sure business logic is worcalifornia california king as per the requirements.
4 Finally, zip the content of the battle folder of the application in the form of battle file and deploy it in Apache Tomcat Webserver.
5 Launch your own web application uperform appropriate URL as exbasiced below in the final 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.                        -->
  <inherit is name='com.google.gwt.user.User'/>

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

  <!-- Specify the app enconsider point course.                         -->
  <enconsider-point course='com.tutorialspoint.claynt.HelloWorld'/>

  <!-- Specify the routes for translatable code                    -->
  <source route='claynt'/>
  <source route='shareddish coloured-coloureddish coloured'/>

</module>

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

body {
   text-align: centre;
   font-family: verdana, sans-serif;
}
h1 {
  font-size: 2em;
  font-weight: bold;
  colour: #777777;
  margin: 40px 0px 70px;
  text-align: centre;
}

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

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

<h1>Hello World</h1>
<div id="gwtContainer"></div>

</body>
</html>

I modified HTML a small bit from previous example. Here I generated a placeholder <div>…</div> where we will insert a few content uperform our enconsider point java course. So permit us have following content of Java file src/com.tutorialspoint/HelloWorld.java.

package com.tutorialspoint.claynt;

iminterface com.google.gwt.core.claynt.EnconsiderPoint;
iminterface com.google.gwt.user.claynt.ui.HTML;
iminterface com.google.gwt.user.claynt.ui.RootPanel;

public course HelloWorld implements EnconsiderPoint {
   public void onModuleLoad() {
      HTML html = brand new HTML("<p>Welcome to GWT application</p>");
      
      RootPanel.get("gwtContainer").add(html);
   }
}

Here we generated on basic widgest HTML and added it inaspect the div tag having id="gwtContainer". We will study various GWT widgets in coming chapters.

Once you are ready with all the modifys done, permit us compile and operate the application in makement mode as we did in GWT – Create Application chapter. If everyslimg is great with your own application, this particular particular will produce following result:

GWT Application Result2

Create WAR File

Now our applictaion is worcalifornia california king great and we are ready to exinterface it as a battle file. Follow the following steps:

  • Go into your own project's battle immediateory C:workspaceHelloWorldbattle

  • Select all the files & folders available inaspect battle immediateory.

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

  • Rename HelloWorld.zip to HelloWorld.battle.

Deploy WAR file

  • Stop the tomcat server.

  • Copy the HelloWorld.battle file to tomcat installation immediateory > webapps folder.

  • Start the tomcat server.

  • Look inaspect webapps immediateory, presently there should be a folder helloworld got generated.

  • Now HelloWorld.battle is successcompallowey deployed in Tomcat Webserver main.

Run Application

Enter a url in web blineser: http://localhost:8080/HelloWorld to launch the application

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

GWT Application Result3

GWT – Style with CSS

GWT widgets rely on cascading style sheets (CSS) for visual styling. By default, the course name for every component is gwt-<coursename>. 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 packagees a bigr font, you could put the following rule in your own application's CSS file:

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

By default, npossibly the blineser nor GWT generates default id attributes for widgets. You must explicitly generate 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 bigr font, you could put the following rule in your own application's CSS file:

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

To set the id for a GWT widget, retrieve it is DOM Element and then set the id attribute as follows:

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

CSS Styling APIs

There are many kind of kind of APIs available to hangle CSS setting for any kind of kind of GWT widget. Following are couple of iminterfaceant APIs which will help you in your own day to day web programming uperform GWT:

S.N. API & Description
1 public void setStyleName(java.lang.String style)
This method will clear any kind of kind of existing styles and set the widget style to the brand new CSS course provided uperform style.
2 public void addStyleName(java.lang.String style)
This method will add a 2ndary or dependent style name to the widget. A 2ndary style name is an additional style name that is,so if presently there were any kind of kind of previous style names applayd they are kept.
3 public void removeStyleName(java.lang.String style)
This method will remove given style from the widget and maintains any kind of kind of others bumociated with the widget.
4 public java.lang.String getStyleName()
This method gets all of the object's style names, as a space-separated list.
5 public void setStylePrimaryName(java.lang.String style)
This method sets the object's primary style name and updates all dependent style names.

For example, permit's degreat 2 brand new styles which we will apply to a text:

.gwt-Big-Text{ 
   font-size:150%;
}
.gwt-Small-Text{ 
   font-size:75%;
}
.gwt-Red-Text{ 
   colour:reddish coloured-coloureddish coloured;
}

Now you can use setStyleName(Style) to modify the default setting to brand new setting. After applying the below rule, a text's font will become big:

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

We can apply a 2ndary CSS rule on the extake action same widget to modify it is colour as follows:

txtWidget.addStyleName("gwt-Red-Text");

Uperform above method you can add as many kind of kind of styles as you like to apply on a widget. If you remove preliminary style from the button widget then 2nd 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 it is widget course for example gwt-Button for Button widgets. When we add and remove style names uperform AddStyleName() method, those styles are calbrought 2ndary styles.

The final appearance of a widget is determined simply by the sum of all the 2ndary styles added to it, plus it is primary style. You set the primary style of a widget with the setStylePrimaryName(String) method. To illustrate, permit's say we have a Label widget. In our CSS file, we have the following rules degreatd:

.MyText {
  colour: blue;
}

.BigText {
  font-size: big;
}

.LoudText {
  font-weight:  bold;
}

Let's suppose we want a particular label widget to always display blue text, and in a few cases, use a bigr, bold font for added emphasis. We could do a fewslimg like this particular particular:

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

// later on, to very grab the user's attention
a fewText.addStyleName("BigText");
a fewText.addStyleName("LoudText");
...

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

Associating CSS Files

There are multiple approaches for bumociating CSS files with your own module. Modern GWT applications typically use a combination of CssResource and UiBinder. We are uperform only preliminary approach in our examples.

  • Uperform a <link> tag in the host HTML page.

  • Uperform the <stylesheet> element in the module XML file.

  • Uperform a CssResource contained wislim a ClayntBundle.

  • Uperform an inrange <ui:style> element in a UiBinder template.

GWT CSS Example

This example will take you through basic steps to apply various CSS rules on your own GWT widgest. Let us have worcalifornia california king Eclipse IDE asizey with GWT plug in place and follow the following steps to generate a GWT application:

Step Description
1 Create a project with a name HelloWorld below a package com.tutorialspoint as exbasiced in the GWT – Create Application chapter.
2 Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorld.html and HelloWorld.java as exbasiced below. Keep rest of the files unmodifyd.
3 Compile and operate the application 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.                        -->
  <inherit is name='com.google.gwt.user.User'/>

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

  <!-- Specify the app enconsider point course.                         -->
  <enconsider-point course='com.tutorialspoint.claynt.HelloWorld'/>

  <!-- Specify the routes for translatable code                    -->
  <source route='claynt'/>
  <source route='shareddish coloured-coloureddish coloured'/>

</module>

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

body{
   text-align: centre;
   font-family: verdana, sans-serif;
}
h1{
   font-size: 2em;
   font-weight: bold;
   colour: #777777;
   margin: 40px 0px 70px;
   text-align: centre;
}
.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 battle/HelloWorld.html to accomodate 2 buttons.

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

<div id="mytext"><h1>Hello, World!</h1></div>
<div id="gwtGreenButton"></div>
<div id="gwtRedButton"></div>

</body>
</html>

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

package com.tutorialspoint.claynt;

iminterface com.google.gwt.core.claynt.EnconsiderPoint;
iminterface com.google.gwt.alsot.dom.claynt.ClickEvent;
iminterface com.google.gwt.alsot.dom.claynt.ClickHandler;
iminterface com.google.gwt.user.claynt.ui.Button;
iminterface com.google.gwt.user.claynt.ui.HTML;
iminterface com.google.gwt.user.claynt.ui.RootPanel;

public course HelloWorld implements EnconsiderPoint {
   public void onModuleLoad() {
     
   // add button to modify font to big when clicked.
   Button Btn1 = brand new Button("Big Text");
   Btn1.addClickHandler(brand new ClickHandler() {
      public void onClick(ClickEvent alsot) {
         RootPanel.get("mytext").setStyleName("gwt-Big-Text");
      }
   });

   // add button to modify font to small when clicked.
   Button Btn2 = brand new Button("Small Text");
   Btn2.addClickHandler(brand new ClickHandler() {
      public void onClick(ClickEvent alsot) {
         RootPanel.get("mytext").setStyleName("gwt-Small-Text");
      }
   });

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

Once you are ready with all the modifys done, permit us compile and operate the application in makement mode as we did in GWT – Create Application chapter. If everyslimg is great with your own application, this particular particular will produce following result:

GWT CSS Application Result

Now consider cliccalifornia california king on the 2 buttons displayed and observe "Hello, World!" text which maintains changing it is font upon cliccalifornia california king on the 2 buttons.

GWT – Widgets

Every user interface conaspectrs the following 3 main aspects:

  • UI elements : Thes are the core visual elements the user alsotually sees and intertake actionions with. GWT provides a huge list of widely used and common elements varying from basic to complex which we will cover in this particular particular tutorial.

  • Layout presently there’s: They degreat how UI elements should be body organised on the screen and provide a final look and feel to the GUI (Graphical User Interface). This part will be covereddish coloured-coloureddish coloured in Layout presently there chapter.

  • Behavior: These are alsots which occur when the user intertake actionions with UI elements. This part will be covereddish coloured-coloureddish coloured in Event Handling chapter.

GWT UI Elements:

The GWT library provides coursees in a well-degreatd course hierarchy to generate complex web-based user interfaces. All coursees in this particular particular component hierarchy has been derived from the UIObject base course as shown below:

GWT Components

Every Basic UI widget inherit is properlink ups from Widget course which in turn inherit is properlink ups from UIObject. Tree and Menu will be covereddish coloured-coloureddish coloured in complex widgets tutorial.

S.N. Widget & Description
1 GWT UIObject Clbum
This widget contains text, not interpreted as HTML uperform a <div>element, cauperform it to be displayed with block layout presently there.
2 GWT Widget Clbum
This widget can contain HTML text and displays the html content uperform a <div> element, cauperform it to be displayed with block layout presently there.

Basic Widgets

Following are couple of iminterfaceant Basic Widgets:

S.N. Widget & Description
1 Label
This widget contains text, not interpreted as HTML uperform a <div>element, cauperform it to be displayed with block layout presently there.
2 HTML
This widget can contain HTML text and displays the html content uperform a <div> element, cauperform it to be displayed with block layout presently there.
3 Image
This widget displays an image at a given URL.
4 Anchor
This widget represents a basic <a> element.

Form Widgets

Form widgets permit is users to input data and provides them intertake actionionion cappossible with the application. Every Form widget inherit is properlink ups from Widget course which in turn inherit is properlink ups from UIObject and Wigdet coursees.

Following are couple of iminterfaceant Form Widgets:

S.N. Widget & Description
1 Button
This widget represents a standard push button.
2 PushButton
This widget represents a normal push button with custom styling.
3 ToggleButton
This widget represents a stylish stateful button which permit is the user to toggle between up and down states.
4 CheckBox
This widget represents a standard check package widget. This course furthermore serves as a base course for RadioButton.
5 RadioButton
This widget represents a mutually-exclusive selection stereo stations button widget.
6 ListBox
This widget represents a list of choices to the user, possibly as a list package or as a fall-down list.
7 SuggestBox
This widget represents a text package or text area which displays a pre-configureddish coloured-coloureddish coloured set of selections that go with the user's input. Each SuggestBox is bumociated with a performle SuggestOracle. The SuggestOracle is used to provide a set of selections given a specific query string.
8 TextBox
This widget represents a performle range text package.
9 PbumwordTextBox
This widget represents a text package that visually masks it is input to pralsot eavesfallping..
10 TextArea
This widget represents a text package that permit is multiple ranges of text to be entereddish coloured-coloureddish coloured.
11 RichTextArea
This widget represents a wealthy text editor that permit is complex styling 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.

Complex Widgets

Complex widgets permit is users to advanced intertake actionionion cappossible with the application. Every Complex widget inherit is properlink ups from Widget course which in turn inherit is properlink ups from UIObject.

Following are couple of iminterfaceant Complex Widgets:

S.N. Widget & Description
1 Tree
This widget represents a standard hierarchical tree widget. The tree contains a hierarchy of TreeItems that the user can open, shut, and select.
2 MenuBar
This widget represents a standard menu bar widget. A menu bar can contain any kind of kind of number of menu items, every of which can possibly 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 see of a tree. This widget will only work in standards mode, which requires that the HTML page in which it is operate have an explicit <!DOCTYPE> declaration.
5 CellList
This widget represents a performle column list of cellularulars.
6 CellTable
This widget represents a tabular see that supinterfaces paging and columns.
7 CellBlineser
This widget represents a blinesable see of a tree in which only a performle 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 operate have an explicit <!DOCTYPE> declaration.

GWT – Layout presently there Panels

Layout presently there Panels can contain other widgets. These panels manages the way widgets to be shown on User Interface. Every Panel widget inherit is properlink ups from Panel course which in turn inherit is properlink ups from Widget course and which in turn inherit is properlink ups from UIObject course.

S.N. Widget & Description
1 GWT UIObject Clbum
This widget contains text, not interpreted as HTML uperform a <div>element, cauperform it to be displayed with block layout presently there.
2 GWT Widget Clbum
This widget can contain HTML text and displays the html content uperform a <div> element, cauperform it to be displayed with block layout presently there.
3 GWT Panel Clbum
This is an is the abstrtake actionion base course for all panels, which are widgets that can contain other widgets.

Layout presently there Panels

Following are couple of iminterfaceant Layout presently there Panels:

S.N. Widget & Description
1 FlowPanel
This widget represents a panel that formats it is kid widgets uperform the default HTML layout presently there behavior.
2 HorizontalPanel
This widget represents a panel that lays all of it is widgets out presently there in a performle horizontal column.
3 VerticalPanel
This widget represents a panel that lays all of it is widgets out presently there in a performle vertical column.
4 HorizontalSplitPanel
This widget represents a panel that arranges 2 widgets in a performle horizontal line and permit is the user to intertake actionionively modify the prointerfaceion of the width dedicated to every of the 2 widgets. Widgets contained wislim a HorizontalSplitPanel will be automatically decorated with scrollbars when essential.
5 VerticalSplitPanel
This widget represents a A panel that arranges 2 widgets in a performle vertical column and permit is the user to intertake actionionively modify the prointerfaceion of the height dedicated to every of the 2 widgets. Widgets contained wislim a VertialSplitPanel will be automatically decorated with scrollbars when essential.
6 FlexTable
This widget represents a flexible table that generates cellularulars on demand. It can be jagged (that is, every line can contain a various number of cellularulars) and individual cellularulars can be set to span multiple lines or columns.
7 Grid
This widget represents a A rectangular grid that can contain text, html, or a kid Widget wislim it is cellularulars. It must be resized explicitly to the desireddish coloured-coloureddish coloured number of lines and columns.
8 DeckPanel
panel that displays all of it is kid widgets in a 'deck', where only one can be visible at a time. It is used simply by TabPanel.
9 DockPanel
This widget represents a panel that lays it is kid widgets out presently there "docked" at it is out presently thereer advantages, and permit is it is final widget to take up the remaining space in it is centre.
10 HTMLPanel
This widget represents a panel that contains HTML, and which can attach kid widgets to identified elements wislim that HTML.
11 TabPanel
This widget represents a panel that represents a tabbed set of pages, every of which contains an additional widget. It’s kid widgets are shown as the user selects the various tabs bumociated with them. The tabs can contain arbitrary HTML.
12 Composit down downe
This widget represents a type of widget that can wrap an additional widget, hiding the wrapped widget's methods. When added to a panel, a composit down downe behaves extake actionionly as if the widget it wraps had been added.
13 SimplePanel
This widget represents a Base course for panels that contain only one widget.
14 ScrollPanel
This widget represents a basic panel that wraps it is contents in a scrollable area
15 FocusPanel
This widget represents a basic panel that generates it is contents focusable, and adds the possible to capture mouse and keytable alsots.
16 FormPanel
This widget represents a basic panel that generates it is contents focusable, and adds the possible to capture mouse and keytable alsots.
17 PopupPanel
This widget represents a panel that can pop up over other widgets. It overlays the blineser's claynt area (and any kind of kind of previously-generated popups).
18 DialogBox
This widget represents a form of popup that has a caption area at the top and can be dragged simply by the user. Unlike a PopupPanel, calls to PopupPanel.setWidth(String) and PopupPanel.setHeight(String) will set the width and height of the dialog package it iself, also if a widget has not been added as yet.

GWT – Event Handling

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

  • A listener interface degreats one or more methods that the widget calls to announce an alsot. GWT provides a list of interfaces corresponding to various feasible alsots.

  • A course wishing to receive alsots of a particular type implements the bumociated handler interface and then compenableees a reference to it iself to the widget to subscribe to a set of alsots.

For example, the Button course publishes click alsots so you will have to write a course to implement ClickHandler to handle click alsot.

Event Handler Interfaces

All GWT alsot handlers have been extended from EventHandler interface and every handler has only a performle method with a performle argument. This argument is always an object of bumociated alsot type. Each alsot object have lots of methods to manipulate the compenableeed alsot object. For example for click alsot you will have to write your own handler as follows:

/**
 * generate a custom click handler which will call 
 * onClick method when button is clicked.
 */
public course MyClickHandler implements ClickHandler {
   @Override
   public void onClick(ClickEvent alsot) {
      Window.alert("Hello World!");
   }
}

Now any kind of kind of course wishing to receive click alsots will call addClickHandler() to register an alsot handler as follows:

/**
 * generate button and attach click handler
 */
Button button = brand new Button("Click Me!");
button.addClickHandler(brand new MyClickHandler());

Each widget supinterfaceing an alsot type will have a method of the form HandlerRegistration addFooHandler(FooEvent) where Foo is the take actionionual alsot like Click, Error, KeyPress etc.

Following is the list of iminterfaceant GWT alsot handlers and bumociated alsots and handler registration methods:

S.N. Event Interface Event Method & Description
1 BeforeSelectionHandler<I> void onBeforeSelection(BeforeSelectionEvent<I> alsot);
Calbrought when BeforeSelectionEvent is fireddish coloured-coloureddish coloured.
2 BlurHandler void onBlur(BlurEvent alsot);
Calbrought when BlurEvent is fireddish coloured-coloureddish coloured.
3 ChangeHandler void onChange(ChangeEvent alsot) ;
Calbrought when a modify alsot is fireddish coloured-coloureddish coloured.
4 ClickHandler void onClick(ClickEvent alsot);
Calbrought when a native click alsot is fireddish coloured-coloureddish coloured.
5 CloseHandler<T> void onClose(CloseEvent<T> alsot) ;
Calbrought when CloseEvent is fireddish coloured-coloureddish coloured.
6 ContextMenuHandler void onContextMenu(ContextMenuEvent alsot);
Calbrought when a native context menu alsot is fireddish coloured-coloureddish coloured.
7 DoubleClickHandler void onDoubleClick(DoubleClickEvent alsot);
Calbrought when a DoubleClickEvent is fireddish coloured-coloureddish coloured.
8 ErrorHandler void onError(ErrorEvent alsot);
Calbrought when ErrorEvent is fireddish coloured-coloureddish coloured.
9 FocusHandler void onFocus(FocusEvent alsot) ;
Calbrought when FocusEvent is fireddish coloured-coloureddish coloured.
10 FormPanel.SubmitComppermiteHandler void onSubmitComppermite(FormPanel.SubmitComppermiteEvent alsot) ;
Fireddish coloured-coloureddish coloured when a form has been submitted successcompallowey.
11 FormPanel.SubmitHandler void onSubmit(FormPanel.SubmitEvent alsot);
Fireddish coloured-coloureddish coloured when the form is submitted.
12 KeyDownHandler void onKeyDown(KeyDownEvent alsot);
Calbrought when KeyDownEvent is fireddish coloured-coloureddish coloured.
13 KeyPressHandler void onKeyPress(KeyPressEvent alsot) ;
Calbrought when KeyPressEvent is fireddish coloured-coloureddish coloured.
14 KeyUpHandler void onKeyUp(KeyUpEvent alsot) ;
Calbrought when KeyUpEvent is fireddish coloured-coloureddish coloured.
15 LoadHandler void onLoad(LoadEvent alsot);
Calbrought when LoadEvent is fireddish coloured-coloureddish coloured.
16 MouseDownHandler void onMouseDown(MouseDownEvent alsot) ;
Calbrought when MouseDown is fireddish coloured-coloureddish coloured.
17 MouseMoveHandler void onMouseMove(MouseMoveEvent alsot);
Calbrought when MouseMoveEvent is fireddish coloured-coloureddish coloured.
18 MouseOutHandler void onMouseOut(MouseOutEvent alsot) ;
Calbrought when MouseOutEvent is fireddish coloured-coloureddish coloured.
19 MouseOverHandler void onMouseOver(MouseOverEvent alsot);
Calbrought when MouseOverEvent is fireddish coloured-coloureddish coloured.
20 MouseUpHandler void onMouseUp(MouseUpEvent alsot) ;
Calbrought when MouseUpEvent is fireddish coloured-coloureddish coloured.
21 MouseWheelHandler void onMouseWheel(MouseWheelEvent alsot) ;
Calbrought when MouseWheelEvent is fireddish coloured-coloureddish coloured.
22 ResizeHandler void onResize(ResizeEvent alsot) ;
Fireddish coloured-coloureddish coloured when the widget is resized.
23 ScrollHandler void onScroll(ScrollEvent alsot) ;
Calbrought when ScrollEvent is fireddish coloured-coloureddish coloured.
24 SelectionHandler<I> void onSelection(SelectionEvent<I> alsot) ;
Calbrought when SelectionEvent is fireddish coloured-coloureddish coloured.
25 ValueChangeHandler<I> void onValueChange(ValueChangeEvent<I> alsot) ;
Calbrought when ValueChangeEvent is fireddish coloured-coloureddish coloured.
26 Window.CloperformHandler void onWindowCloperform(Window.CloperformEvent alsot) ;
Fireddish coloured-coloureddish coloured simply before the blineser window shuts or navigates to a various sit down downe.
27 Window.ScrollHandler void onWindowScroll(Window.ScrollEvent alsot) ;
Fireddish coloured-coloureddish coloured when the blineser window is scrolbrought.

Event Methods

As mentioned earlayr, every handler has a performle method with a performle argument which holds the alsot object, for example void onClick(ClickEvent alsot) or void onKeyDown(KeyDownEvent alsot). The alsot objects like ClickEvent and KeyDownEvent has couple of common methods which are listed below:

S.N. Method & Description
1 protected void dispatch(ClickHandler handler) This method Should only be calbrought simply by HandlerManager
2 DomEvent.Type <FooHandler> getAssociatedType() This method returns the type used to register Foo alsot.
3 static DomEvent.Type<FooHandler> getType() This method gets the alsot type bumociated with Foo alsots.
4 public java.lang.Object getSource() This method returns the source that final fireddish coloured-coloureddish coloured this particular particular alsot.
5 protected final boolean isLive() This method returns whether the alsot is reside.
6 protected void eliminate() This method eliminates the alsot

Example

This example will take you through basic steps to show usage of a Click Event and KeyDown Event handling in GWT. Follow the following steps to update the GWT application we generated in GWT – Create Application chapter:

Step Description
1 Create a project with a name HelloWorld below a package com.tutorialspoint as exbasiced in the GWT – Create Application chapter.
2 Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorld.html and HelloWorld.java as exbasiced below. Keep rest of the files unmodifyd.
3 Compile and operate the application 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.                        -->
  <inherit is name='com.google.gwt.user.User'/>

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

  <!-- Specify the app enconsider point course.                         -->
  <enconsider-point course='com.tutorialspoint.claynt.HelloWorld'/>

  <!-- Specify the routes for translatable code                    -->
  <source route='claynt'/>
  <source route='shareddish coloured-coloureddish coloured'/>

</module>

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

body{
   text-align: centre;
   font-family: verdana, sans-serif;
}
h1{
   font-size: 2em;
   font-weight: bold;
   colour: #777777;
   margin: 40px 0px 70px;
   text-align: centre;
}

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

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

<h1>Event Handling Demonstration</h1>
<div id="gwtContainer"></div>

</body>
</html>

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

package com.tutorialspoint.claynt;

iminterface com.google.gwt.core.claynt.EnconsiderPoint;
iminterface com.google.gwt.alsot.dom.claynt.ClickEvent;
iminterface com.google.gwt.alsot.dom.claynt.ClickHandler;
iminterface com.google.gwt.alsot.dom.claynt.KeyCodes;
iminterface com.google.gwt.alsot.dom.claynt.KeyDownEvent;
iminterface com.google.gwt.alsot.dom.claynt.KeyDownHandler;
iminterface com.google.gwt.user.claynt.Window;
iminterface com.google.gwt.user.claynt.ui.Button;
iminterface com.google.gwt.user.claynt.ui.DecoratorPanel;
iminterface com.google.gwt.user.claynt.ui.HasHorizontalAlignment;
iminterface com.google.gwt.user.claynt.ui.RootPanel;
iminterface com.google.gwt.user.claynt.ui.TextBox;
iminterface com.google.gwt.user.claynt.ui.VerticalPanel;

public course HelloWorld implements EnconsiderPoint {
   public void onModuleLoad() {
      /**
       * generate textpackage and attach key down handler
       */
      TextBox textBox = brand new TextBox(); 
      textBox.addKeyDownHandler(brand new MyKeyDownHandler());

      /*
       * generate button and attach click handler
       */
      Button button = brand new Button("Click Me!");
      button.addClickHandler(brand new MyClickHandler());

      VerticalPanel panel = brand new VerticalPanel();
      panel.setSpacing(10);
      panel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
      panel.setSize("300", "100");
      panel.add(textBox);
      panel.add(button);

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

   /** 
    * generate a custom click handler which will call 
    * onClick method when button is clicked.
    */
   private course MyClickHandler implements ClickHandler {
      @Override
      public void onClick(ClickEvent alsot) {
         Window.alert("Hello World!");
      }
   }

   /**
    * generate a custom key down handler which will call 
    * onKeyDown method when a key is down in textpackage.
    */
   private course MyKeyDownHandler implements KeyDownHandler {
      @Override
      public void onKeyDown(KeyDownEvent alsot) {
         if(alsot.getNativeKeyCode() == KeyCodes.KEY_ENTER){
            Window.alert(((TextBox)alsot.getSource()).getValue());
         }
      }
   }
}

Once you are ready with all the modifys done, permit us compile and operate the application in makement mode as we did in GWT – Create Application chapter. If everyslimg is great with your own application, this particular particular will produce following result:

GWT Event Handling

GWT – Custom Widgets

GWT provides 3 ways to generate custom user interface elements. There are 3 general strategies to follow:

  • Create a widget simply by extending Composit down downe Clbum: This is the many kind of kind of common and easiest way to generate custom widgets. Here you can use existing widgets to generate composit down downe see with custom properlink ups.

  • Create a widget uperform GWT DOM API in JAVA: GWT basic widgets are generated in this particular particular way. Still it is an extremely complicated way to generate custom widget and should be used cautiously.

  • Use JavaScript and wrap it in a widget uperform JSNI: This should generally only be done as a final resort. Conaspectring the combination-blineser implications of the native methods, it becomes very complicated and furthermore becomes more difficult to debug.

Create Custom Widget with Composit down downe Clbum

This example will take you through basic steps to show creation of a Custom Widget in GWT. Follow the following steps to update the GWT application we generated in GWT – Basic Widgets chapter:

Here we are going to generate a custom widget simply by extending Composit down downe course, which is the easiest way to build custom widgets.

Step Description
1 Create a project with a name HelloWorld below a package com.tutorialspoint as exbasiced in the GWT – Create Application chapter.
2 Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorld.html and HelloWorld.java as exbasiced below. Keep rest of the files unmodifyd.
3 Compile and operate the application 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.                        -->
  <inherit is name='com.google.gwt.user.User'/>

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

  <!-- Specify the app enconsider point course.                         -->
  <enconsider-point course='com.tutorialspoint.claynt.HelloWorld'/>

  <!-- Specify the routes for translatable code                    -->
  <source route='claynt'/>
  <source route='shareddish coloured-coloureddish coloured'/>

</module>

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

body{
   text-align: centre;
   font-family: verdana, sans-serif;
}
h1{
   font-size: 2em;
   font-weight: bold;
   colour: #777777;
   margin: 40px 0px 70px;
   text-align: centre;
}

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

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

<h1>Custom Widget Demonstration</h1>
<div id="gwtContainer"></div>

</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.claynt;

iminterface com.google.gwt.core.claynt.EnconsiderPoint;
iminterface com.google.gwt.alsot.dom.claynt.ClickEvent;
iminterface com.google.gwt.alsot.dom.claynt.ClickHandler;
iminterface com.google.gwt.user.claynt.ui.CheckBox;
iminterface com.google.gwt.user.claynt.ui.Composit down downe;
iminterface com.google.gwt.user.claynt.ui.HorizontalPanel;
iminterface com.google.gwt.user.claynt.ui.RootPanel;
iminterface com.google.gwt.user.claynt.ui.TextBox;

public course HelloWorld implements EnconsiderPoint {

   /**
   * A composit down downe of a TextBox and a CheckBox that optionally enables it.
   */
   private static course OptionalTextBox extends Composit down downe implements
   ClickHandler {

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

      public boolean isEnabbrought() {
         return enabbrought;
      }

      public void setEnabbrought(boolean enabbrought) {
         this particular particular.enabbrought = enabbrought;
      }

      /**
      * Style this particular particular widget uperform .optionalTextWidget CSS course.<br/>
      * Style textpackage uperform .optionalTextBox CSS course.<br/>
      * Style checkpackage uperform .optionalCheckBox CSS course.<br/>
      * Constructs an OptionalTextBox with the given caption 
      * on the check.
      * @param caption the caption to be displayed with the check package
      */
      public OptionalTextBox(String caption) {
         // place the check above the text package uperform a vertical panel.
         HorizontalPanel panel = brand new HorizontalPanel();
         // panel.setBorderWidth(1);
         panel.setSpacing(10);
         panel.add(checkBox);
         panel.add(textBox);

         // all composit down downes must call initWidget() in their particular constructors.
         initWidget(panel);
         
         //set style name for entire widget
         setStyleName("optionalTextWidget");
         
         //set style name for text package
         textBox.setStyleName("optionalTextBox");
         
         //set style name for check package
         checkBox.setStyleName("optionalCheckBox");
         textBox.setWidth("200");
         
         // Set the check package's caption, and check it simply by default.
         checkBox.setText(caption);
         checkBox.setValue(enabbrought);
         checkBox.addClickHandler(this particular particular);
         enableTextBox(enabbrought,checkBox.getValue());
      }

      public void onClick(ClickEvent alsot) {
         if (alsot.getSource() == checkBox) {
            // When the check package is clicked,
            //update the text package's enabbrought state.
            enableTextBox(enabbrought,checkBox.getValue());
         }
      }

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

   public void onModuleLoad() {
      // Create an optional text package and add it to the main panel.
      OptionalTextBox otb = brand new OptionalTextBox(
      "Want to exbasic the solution?");
      otb.setEnabbrought(true);
      RootPanel.get().add(otb);
   }    
} 

Once you are ready with all the modifys done, permit us compile and operate the application in makement mode as we did in GWT – Create Application chapter. If everyslimg is great with your own application, this particular particular will produce following result:

GWT Custom Widget

You can notice following points

  • Creation of Custom Widget simply by extending Composit down downe widget is quite easy.

  • We've generated a widget with GWT inbuilt widgets, TextBox and CheckBox thus uperform the concept of reuspossible.

  • TextBox get disabbrought/enabbrought depending on state of checkpackage. We've provided an API to enable/disable the manage.

  • We've exposed internal widgets styles via documented CSS styles.

GWT – Uperform UiBinder

Introduction

  • The UiBinder is a framework styleed to separate Functionality and View of User Interface.

  • The UiBinder framework permit is makeers to build gwt applications as HTML pages with GWT widgets configureddish coloured-coloureddish coloured throughout presently there them.

  • The UiBinder framework generates easier collaboration with UI styleers 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 extake actionionly extake actionly what JSP is to Servpermit is.

UiBinder workflow

Step 1: Create UI Declaration XML File

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

<ui:UiBinder xmlns:ui='urn:ui:com.google.gwt.uibinder'
   xmlns:gwt='urn:iminterface:com.google.gwt.user.claynt.ui' 
   xmlns:res='urn:with:com.tutorialspoint.claynt.LoginResources'>
   <ui:with type="com.tutorialspoint.claynt.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="comppermitionLabel1" />
<gwt:Label ui:field="comppermitionLabel2" />       

Step 3: Create Java counterpart of UI XML

Create Java based counterpart of XML based layout presently there simply by extending Composit down downe widget. We've generated a Login.java file in our example.

package com.tutorialspoint.claynt;
...
public course Login extends Composit down downe {
...
}

Step 4: Bind Java UI fields with UiField annotation

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

public course Login extends Composit down downe {
   ...
   @UiField
   Label comppermitionLabel1;

   @UiField
   Label comppermitionLabel2;  
   ...
}

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

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

public course Login extends Composit down downe {

   private static LoginUiBinder uiBinder = GWT.generate(LoginUiBinder.course);

   /*
   * @UiTemplate is not mandatory but permit is multiple XML templates
   * to be used for the extake action same widget. 
   * Default file loaded will be <course-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;
   colour: #000000;
   font-size: 11px;
   text-align: left;
}
...

Step 7: Create Java based Resource File for CSS File

package com.tutorialspoint.claynt;
...
public interface LoginResources extends ClayntBundle {
   public 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 uperform Contructor of Java based widget course Login.java

public Login() {
   this particular particular.res = GWT.generate(LoginResources.course);
   res.style().ensureInjected();
   initWidget(uiBinder.generateAndBindUi(this particular particular));
}

UIBinder Comppermite Example

This example will take you through basic steps to show usage of a UIBinder in GWT. Follow the following steps to update the GWT application we generated in GWT – Create Application chapter:

Step Description
1 Create a project with a name HelloWorld below a package com.tutorialspoint as exbasiced in the GWT – Create Application chapter.
2 Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorld.html and HelloWorld.java as exbasiced below. Keep rest of the files unmodifyd.
3 Compile and operate the application 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.                        -->
  <inherit is name='com.google.gwt.user.User'/>

  <!-- Inherit the default GWT style sheet.                       -->
  <inherit is name='com.google.gwt.user.theme.thoroughly clean.Clean'/>
  <!-- Inherit the UiBinder module.                               -->
  <inherit is name="com.google.gwt.uibinder.UiBinder"/>
  <!-- Specify the app enconsider point course.                         -->
  <enconsider-point course='com.tutorialspoint.claynt.HelloWorld'/>
  
  <!-- Specify the routes for translatable code                    -->
  <source route='claynt'/>
  <source route='shareddish coloured-coloureddish coloured'/>

</module>

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

body{
   text-align: centre;
   font-family: verdana, sans-serif;
}
h1{
   font-size: 2em;
   font-weight: bold;
   colour: #777777;
   margin: 40px 0px 70px;
   text-align: centre;
}

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

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

<h1>UiBinder Demonstration</h1>
<div id="gwtContainer"></div>

</body>
</html>

Now generate a brand new UiBinder template and owner course (File -> New -> UiBinder).

GWT UiBinder Wizard Step 1

Choose the claynt package for the project and then name it Login. Leave all of the other defaults.Click Finish button and the plugin will generate a brand new UiBinder template and owner course.

GWT UiBinder Wizard Step 2

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

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

.reddish coloured-coloureddish colouredText {
   font-family: Arial, Sans-serif;
   colour: #ff0000;
   font-size: 11px;
   text-align: left;
}

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

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

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

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

package com.tutorialspoint.claynt;

iminterface com.google.gwt.resources.claynt.ClayntBundle;
iminterface com.google.gwt.resources.claynt.CssResource;

public interface LoginResources extends ClayntBundle {
   /**
   * Sample CssResource.
   */
   public interface MyCss extends CssResource {
      String blackText();

      String reddish coloured-coloureddish colouredText();

      String loginButton();

      String package();

      String background();
   }

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

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

<ui:UiBinder xmlns:ui='urn:ui:com.google.gwt.uibinder'
   xmlns:gwt='urn:iminterface:com.google.gwt.user.claynt.ui' 
   xmlns:res='urn:with:com.tutorialspoint.claynt.LoginResources'>
   <ui:with type="com.tutorialspoint.claynt.LoginResources" field="res">
   </ui:with>
   <gwt:HTMLPanel>
      <div align="centre">
         <gwt:VerticalPanel res:styleName="style.background">
            <gwt:Label text="Login" res:styleName="style.greyText" />
            <gwt:TextBox ui:field="loginBox" res:styleName="style.package" />
            <gwt:Label text="Pbumword" res:styleName="style.greyText" />
            <gwt:PbumwordTextBox ui:field="compenableewordBox" 
            res:styleName="style.package" />
            <gwt:HorizontalPanel verticalAlignment="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.greyText" />
            </gwt:HorizontalPanel>
            <gwt:Label ui:field="comppermitionLabel1" 
            res:styleName="style.greyText" />
            <gwt:Label ui:field="comppermitionLabel2" 
            res:styleName="style.greyText" />
         </gwt:VerticalPanel>
      </div>
   </gwt:HTMLPanel>
</ui:UiBinder> 

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

package com.tutorialspoint.claynt;

iminterface com.google.gwt.core.claynt.GWT;
iminterface com.google.gwt.alsot.dom.claynt.ClickEvent;
iminterface com.google.gwt.alsot.logical.shareddish coloured-coloureddish coloured.ValueChangeEvent;
iminterface com.google.gwt.uibinder.claynt.UiBinder;
iminterface com.google.gwt.uibinder.claynt.UiField;
iminterface com.google.gwt.uibinder.claynt.UiHandler;
iminterface com.google.gwt.uibinder.claynt.UiTemplate;
iminterface com.google.gwt.user.claynt.Window;
iminterface com.google.gwt.user.claynt.ui.Composit down downe;
iminterface com.google.gwt.user.claynt.ui.Label;
iminterface com.google.gwt.user.claynt.ui.TextBox;
iminterface com.google.gwt.user.claynt.ui.Widget;

public course Login extends Composit down downe {

   private static LoginUiBinder uiBinder = GWT.generate(LoginUiBinder.course);

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

   @UiField(provided = true)
   final LoginResources res;

   public Login() {
      this particular particular.res = GWT.generate(LoginResources.course);
      res.style().ensureInjected();
      initWidget(uiBinder.generateAndBindUi(this particular particular));
   }

   @UiField
   TextBox loginBox;

   @UiField
   TextBox compenableewordBox;

   @UiField
   Label comppermitionLabel1;

   @UiField
   Label comppermitionLabel2;

   private Boolean tooShort = false;

   /*
   * Method name is not relevant, the binding is done according to the course
   * of the parameter.
   */
   @UiHandler("buttonSubmit")
   void doClickSubmit(ClickEvent alsot) {
      if (tooShort) {
         Window.alert("Login Successful!");
      } else {
         Window.alert("Login or Pbumword is too short!");
      }
   }

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

   @UiHandler("compenableewordBox")
   void handlePbumwordChange(ValueChangeEvent<String> alsot) {
      if (alsot.getValue().size() < 6) {
         tooShort = true;
         comppermitionLabel2.setText("Pbumword too short (Size must be > 6)");
      } else {
         tooShort = false;
         comppermitionLabel2.setText("");
      }
   }
}

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

package com.tutorialspoint.claynt;

iminterface com.google.gwt.core.claynt.EnconsiderPoint;
iminterface com.google.gwt.user.claynt.ui.RootPanel;

public course HelloWorld implements EnconsiderPoint {
   public void onModuleLoad() {
      RootPanel.get().add(brand new Login());   
   }    
} 

Once you are ready with all the modifys done, permit us compile and operate the application in makement mode as we did in GWT – Create Application chapter. If everyslimg is great with your own application, this particular particular will produce following result:

GWT UiBinder Demo

GWT – RPC Communication

A GWT based application is generally consists of a claynt aspect module and server aspect module. Claynt aspect code operates in blineser and server aspect code operates in web server. Claynt aspect code has to generate an HTTP request accombination the ne2rk to access server aspect data.

RPC, Remote Procedure Call is the mechansim used simply by GWT in which claynt code can immediately executes the server aspect methods.

  • GWT RPC is servpermit based.

  • GWT RPC is asynchronous and claynt is never blocked during communication.

  • Uperform GWT RPC Java objects can be sent immediately between the claynt and the server (which are automatically serialized simply by the GWT framework).

  • Server-aspect servpermit is termed as service.

  • Remote procedure call that is calling methods of server aspect servpermit is from claynt aspect code is referreddish coloured-coloureddish coloured to as invocalifornia california king a service.

GWT RPC Components

Following are the 3 components used in GWT RPC communication mechanism

  • A remote service (server-aspect servpermit) that operates on the server.

  • Claynt code to invoke that service.

  • Java data objects which will be compenableeed between claynt and server.

GWT claynt and server both serialize and deserialize data automatically so makeers are not requireddish coloured-coloureddish coloured to serialize/deserialize objects and data objects can journey over HTTP.

Following diagram is showing the RPC Architecture.

GWT RPC workflow

To start uperform RPC, we're requireddish coloured-coloureddish coloured to follow the GWT conventions.

RPC Communication workflow

Step 1: Create a Serializable Model Clbum

Degreat a java model object at claynt aspect which should be serializable.

public course Message implements Serializable {
   ...
   private String message;
   public Message(){};

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

Step 2: Create a Service Interface

Degreat an interface for service on claynt aspect that extends RemoteService listing all service methods.

Use annotation @RemoteServiceRelativePath to chart the service with a default route of remote servpermit relative to the module base URL.

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

Step 2: Create a Async Service Interface

Degreat an asynchronous interface to service on claynt aspect (at extake action same location as service mentioned above) which will be used in the GWT claynt code.

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

Step 3: Create a Service Implementation Servpermit course

Implement the interface at server aspect and that course should extends RemoteServiceServpermit course.

public course MessageServiceImpl extends RemoteServiceServpermit
   implements MessageService{
   ...
   public Message getMessage(String input) {
      String messageString = "Hello " + input + "!";
      Message message = brand new Message();
      message.setMessage(messageString);
      return message;
   }
}

Step 4: Update Web.xml to include Servpermit declaration

Edit the web application deployment descriptor (web.xml) to include MessageServiceImpl Servpermit declaration.

<web-app>
   ...
   <servpermit>
      <servpermit-name>messageServiceImpl</servpermit-name>
      <servpermit-course>com.tutorialspoint.server.MessageServiceImpl
      </servpermit-course>
   </servpermit>
   <servpermit-chartping>
      <servpermit-name>messageServiceImpl</servpermit-name>
      <url-pattern>/helloworld/message</url-pattern>
   </servpermit-chartping>
</web-app>

Step 5: Make the remote procedure call in Application Code

Create the service proxy course.

MessageServiceAsync messageService = GWT.generate(MessageService.course);

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

course MessageCallBack implements AsyncCallback<Message> {

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

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

Call Remote service when user intertake actionions with UI

public course HelloWorld implements EnconsiderPoint {
   ... 
   public void onModuleLoad() {
   ...
      buttonMessage.addClickHandler(brand new ClickHandler() {			
         @Override
         public void onClick(ClickEvent alsot) {
            messageService.getMessage(txtName.getValue(), 
            brand new MessageCallBack());
         }});
   ...
   }
}

RPC Communication Comppermite Example

This example will take you through basic steps to show example of a RPC Communication in GWT. Follow the following steps to update the GWT application we generated in GWT – Create Application chapter:

Step Description
1 Create a project with a name HelloWorld below a package com.tutorialspoint as exbasiced in the GWT – Create Application chapter.
2 Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorld.html and HelloWorld.java as exbasiced below. Keep rest of the files unmodifyd.
3 Compile and operate the application 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.                        -->
  <inherit is name='com.google.gwt.user.User'/>

  <!-- Inherit the default GWT style sheet.                       -->
  <inherit is name='com.google.gwt.user.theme.thoroughly clean.Clean'/>
  <!-- Inherit the UiBinder module.                               -->
  <inherit is name="com.google.gwt.uibinder.UiBinder"/>
  <!-- Specify the app enconsider point course.                         -->
  <enconsider-point course='com.tutorialspoint.claynt.HelloWorld'/>
  
  <!-- Specify the routes for translatable code                    -->
  <source route='claynt'/>
  <source route='shareddish coloured-coloureddish coloured'/>

</module>

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

body{
   text-align: centre;
   font-family: verdana, sans-serif;
}
h1{
   font-size: 2em;
   font-weight: bold;
   colour: #777777;
   margin: 40px 0px 70px;
   text-align: centre;
}

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

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

<h1>RPC Communication Demonstration</h1>
<div id="gwtContainer"></div>

</body>
</html>

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

package com.tutorialspoint.claynt;

iminterface java.io.Serializable;

public course Message implements Serializable {
 
   private static final sizey serialVersionUID = 1L;
   private String message;
   public Message(){};

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

   public String getMessage() {
      return message;
   }
}

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

package com.tutorialspoint.claynt;

iminterface com.google.gwt.user.claynt.rpc.RemoteService;
iminterface com.google.gwt.user.claynt.rpc.RemoteServiceRelativePath;

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

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

package com.tutorialspoint.claynt;

iminterface com.google.gwt.user.claynt.rpc.AsyncCallback;

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

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

package com.tutorialspoint.server;

iminterface com.google.gwt.user.server.rpc.RemoteServiceServpermit;
iminterface com.tutorialspoint.claynt.Message;
iminterface com.tutorialspoint.claynt.MessageService;

public course MessageServiceImpl extends RemoteServiceServpermit 
   implements MessageService{

   private static final sizey serialVersionUID = 1L;

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

Update the content of the modified web application deployment descriptor battle/WEB-INF/web.xml to include MessageServiceImpl Servpermit declaration .

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

<web-app>
   <!-- Default page to serve -->
   <welcome-file-list>
      <welcome-file>HelloWorld.html</welcome-file>
   </welcome-file-list>
   <servpermit>
      <servpermit-name>messageServiceImpl</servpermit-name>
      <servpermit-course>com.tutorialspoint.server.MessageServiceImpl
      </servpermit-course>
   </servpermit>

   <servpermit-chartping>
      <servpermit-name>messageServiceImpl</servpermit-name>
      <url-pattern>/helloworld/message</url-pattern>
   </servpermit-chartping>
</web-app>

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

package com.tutorialspoint.claynt;

iminterface com.google.gwt.core.claynt.EnconsiderPoint;
iminterface com.google.gwt.core.claynt.GWT;
iminterface com.google.gwt.alsot.dom.claynt.ClickEvent;
iminterface com.google.gwt.alsot.dom.claynt.ClickHandler;
iminterface com.google.gwt.alsot.dom.claynt.KeyCodes;
iminterface com.google.gwt.alsot.dom.claynt.KeyUpEvent;
iminterface com.google.gwt.alsot.dom.claynt.KeyUpHandler;
iminterface com.google.gwt.user.claynt.Window;
iminterface com.google.gwt.user.claynt.rpc.AsyncCallback;
iminterface com.google.gwt.user.claynt.ui.Button;
iminterface com.google.gwt.user.claynt.ui.DecoratorPanel;
iminterface com.google.gwt.user.claynt.ui.HasHorizontalAlignment;
iminterface com.google.gwt.user.claynt.ui.HorizontalPanel;
iminterface com.google.gwt.user.claynt.ui.Label;
iminterface com.google.gwt.user.claynt.ui.RootPanel;
iminterface com.google.gwt.user.claynt.ui.TextBox;
iminterface com.google.gwt.user.claynt.ui.VerticalPanel;

public course HelloWorld implements EnconsiderPoint {
	
   private MessageServiceAsync messageService = 
   GWT.generate(MessageService.course);

   private course MessageCallBack implements AsyncCallback<Message> {
      @Override
      public void onFailure(Thlineable caught) {
         /* server aspect error occureddish coloured-coloureddish coloured */
         Window.alert("Unable to obtain server response: " 
         + caught.getMessage());	
      }
      @Override
      public void onSuccess(Message result) {
          /* server returned result, show user the message */
         Window.alert(result.getMessage());
      }	   
   }

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

      Button buttonMessage = brand new Button("Click Me!");

      buttonMessage.addClickHandler(brand new ClickHandler() {			
      @Override
      public void onClick(ClickEvent alsot) {
         /* generate remote call to server to get the message */
         messageService.getMessage(txtName.getValue(), 
         brand new MessageCallBack());
      }});

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

      VerticalPanel vPanel = brand new VerticalPanel();
      vPanel.setSpacing(10);
      vPanel.add(hPanel);
      vPanel.add(buttonMessage);
      vPanel.setCellHorizontalAlignment(buttonMessage, 
      HasHorizontalAlignment.ALIGN_RIGHT);

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

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

Once you are ready with all the modifys done, permit us compile and operate the application in makement mode as we did in GWT – Create Application chapter. If everyslimg is great with your own application, this particular particular will produce following result:

GWT RPC Demo

GWT – JUnit Integration

GWT provides execellularularent supinterface for automated checcalifornia king of claynt aspect code uperform JUnit checcalifornia king framework. In this particular particular article we'll demonstrate GWT and JUNIT integration.

Download Jdevice archive

JUnit Official Site: http://www.jdevice.org

Download Jdevice-4.10.jar

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

Store the downloaded jar file to a few location on your own computer. We've storeddish coloured-coloureddish coloured 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 Clbum

GWT provides GWTTestCase base course which provides JUnit integration. Running a compibrought course which extends GWTTestCase below JUnit launches the HtmlUnit blineser which serves to emulate your own application behavior during check execution.

GWTTestCase is a derived course from JUnit's TestCase and it can be operate uperform JUnit TestRunner.

Uperform webAppCreator

GWT provides a special command range tool webAppCreator which can generate a starter check case for us, plus ant targets and eclipse launch configs for checcalifornia king in both makement mode and itemion mode.

Open command prompt and go to C: > GWT_WORKSPACE > where you want to generate a brand new project with check supinterface.Run the following command

C:GWT_WORKSPACE>C:GWTgwt-2.1.0webAppCreator 
                -out presently there HelloWorld 
                -jdevice C:JUNITjdevice-4.10.jar 
                com.tutorialspoint.HelloWorld

Noteworthy Points

  • We are executing webAppCreator command range utility.

  • HelloWorld is the name of the project to be generated

  • -jdevice option instructs webAppCreator to add jdevice suppinterface to project

  • com.tutorialspoint.HelloWorld is the name of the module

Verify the out presently thereput.

Created immediateory HelloWorldsrc
Created immediateory HelloWorldbattle
Created immediateory HelloWorldbattleWEB-INF
Created immediateory HelloWorldbattleWEB-INFlib
Created immediateory HelloWorldsrccomtutorialspoint
Created immediateory HelloWorldsrccomtutorialspointclaynt
Created immediateory HelloWorldsrccomtutorialspointserver
Created immediateory HelloWorldsrccomtutorialspointshareddish coloured-coloureddish coloured
Created immediateory HelloWorldcheckcomtutorialspoint
Created immediateory HelloWorldcheckcomtutorialspointclaynt
Created file HelloWorldsrccomtutorialspointHelloWorld.gwt.xml
Created file HelloWorldbattleHelloWorld.html
Created file HelloWorldbattleHelloWorld.css
Created file HelloWorldbattleWEB-INFweb.xml
Created file HelloWorldsrccomtutorialspointclayntHelloWorld.java
Created file 
HelloWorldsrccomtutorialspointclayntGreetingService.java
Created file 
HelloWorldsrccomtutorialspointclayntGreetingServiceAsync.java
Created file 
HelloWorldsrccomtutorialspointserverGreetingServiceImpl.java
Created file HelloWorldsrccomtutorialspointshareddish coloured-coloureddish colouredFieldVerifier.java
Created file HelloWorldbuild.xml
Created file HelloWorldREADME.txt
Created file HelloWorldcheckcomtutorialspointHelloWorldJUnit.gwt.xml
Created file HelloWorldcheckcomtutorialspointclayntHelloWorldTest.java
Created file HelloWorld.project
Created file HelloWorld.courseroute
Created file HelloWorldHelloWorld.launch
Created file HelloWorldHelloWorldTest-dev.launch
Created file HelloWorldHelloWorldTest-prod.launch

Understanding the check course: HelloWorldTest.java

package com.tutorialspoint.claynt;

iminterface com.tutorialspoint.shareddish coloured-coloureddish coloured.FieldVerifier;
iminterface com.google.gwt.core.claynt.GWT;
iminterface com.google.gwt.jdevice.claynt.GWTTestCase;
iminterface com.google.gwt.user.claynt.rpc.AsyncCallback;
iminterface com.google.gwt.user.claynt.rpc.ServiceDefTarget;

/**
 * GWT JUnit checks must extend GWTTestCase.
 */
public course HelloWorldTest extends GWTTestCase {

   /**
   * must refer to a valid module that sources this particular particular course.
   */
   public String getModuleName() {
      return "com.tutorialspoint.HelloWorldJUnit";
   }

   /**
   * checks the FieldVerifier.
   */
   public void checkFieldVerifier() {
      bumertFalse(FieldVerifier.isValidName(null));
      bumertFalse(FieldVerifier.isValidName(""));
      bumertFalse(FieldVerifier.isValidName("a"));
      bumertFalse(FieldVerifier.isValidName("ab"));
      bumertFalse(FieldVerifier.isValidName("abc"));
      bumertTrue(FieldVerifier.isValidName("abcd"));
   }

   /**
   * this particular particular check will send a request to the server uperform the greetServer
   *  method in GreetingService and verify the response.
   */
   public void checkGreetingService() {
      /* generate the service that we will check. */
      GreetingServiceAsync greetingService = 
      GWT.generate(GreetingService.course);
      ServiceDefTarget target = (ServiceDefTarget) greetingService;
      target.setServiceEnconsiderPoint(GWT.getModuleBaseURL() 
      + "helloworld/greet");

      /* since RPC calls are asynchronous, we will need to wait around 
       for a response after this particular particular check method returns. This range 
       tells the check operatener to wait around up to 10 2nds 
       before timing out presently there. */
      delayTestFinish(10000);

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

         public void onSuccess(String result) {
            /* verify that the response is appropriate. */
            bumertTrue(result.startsWith("Hello, GWT User!"));

            /* now that we have received a response, we need to 
             tell the check operatener that the check is comppermite. 
             You must call compenableeTest() after an asynchronous check 
             compenableees successcompallowey, or the check will time out presently there.*/
            compenableeTest();
         }
      });
   }
}

Noteworthy Points

Sr. Note
1 HelloWorldTest course was generated in the com.tutorialspoint.claynt package below the HelloWorld/check immediateory.
2 HelloWorldTest course will contain device check cases for HelloWorld.
3 HelloWorldTest course extends the GWTTestCase course in the com.google.gwt.jdevice.claynt package.
4 HelloWorldTest course has an abstrtake actionion method (getModuleName) that must return the name of the GWT module. For HelloWorld, this particular particular is com.tutorialspoint.HelloWorldJUnit.
5 HelloWorldTest course is generated with 2 sample check cases checkFieldVerifier, checkSimple. We've added checkGreetingService.
6 These methods use one of the many kind of kind of bumert* functions that it inherit is from the JUnit Assert course, which is an ancestor of GWTTestCase.
7 The bumertTrue(boolean) function bumerts that the boolean argument compenableeed in evaluates to true. If not, the check will fail when operate in JUnit.

GWT – JUnit Integration Comppermite Example

This example will take you through basic steps to show example of JUnit Integration in GWT. Follow the following steps to update the GWT application we generated above

Step Description
1 Iminterface the project with a name HelloWorld in eclipse uperform iminterface existing project wizard (File > Iminterface > General > Existing Projects into workspace ).
2 Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorld.html and HelloWorld.java as exbasiced below. Keep rest of the files unmodifyd.
3 Compile and operate the application to verify the result of the implemented logic.

Following will be the project structure in eclipse.

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.                        -->
  <inherit is name='com.google.gwt.user.User'/>

  <!-- Inherit the default GWT style sheet.                       -->
  <inherit is name='com.google.gwt.user.theme.thoroughly clean.Clean'/>
  <!-- Inherit the UiBinder module.                               -->
  <inherit is name="com.google.gwt.uibinder.UiBinder"/>
  <!-- Specify the app enconsider point course.                         -->
  <enconsider-point course='com.tutorialspoint.claynt.HelloWorld'/>
  
  <!-- Specify the routes for translatable code                    -->
  <source route='claynt'/>
  <source route='shareddish coloured-coloureddish coloured'/>

</module>

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

body{
   text-align: centre;
   font-family: verdana, sans-serif;
}
h1{
   font-size: 2em;
   font-weight: bold;
   colour: #777777;
   margin: 40px 0px 70px;
   text-align: centre;
}

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

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

<h1>JUnit Integration Demonstration</h1>
<div id="gwtContainer"></div>

</body>
</html>

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

package com.tutorialspoint.claynt;

iminterface com.google.gwt.core.claynt.EnconsiderPoint;
iminterface com.google.gwt.core.claynt.GWT;
iminterface com.google.gwt.alsot.dom.claynt.ClickEvent;
iminterface com.google.gwt.alsot.dom.claynt.ClickHandler;
iminterface com.google.gwt.alsot.dom.claynt.KeyCodes;
iminterface com.google.gwt.alsot.dom.claynt.KeyUpEvent;
iminterface com.google.gwt.alsot.dom.claynt.KeyUpHandler;
iminterface com.google.gwt.user.claynt.Window;
iminterface com.google.gwt.user.claynt.rpc.AsyncCallback;
iminterface com.google.gwt.user.claynt.ui.Button;
iminterface com.google.gwt.user.claynt.ui.DecoratorPanel;
iminterface com.google.gwt.user.claynt.ui.HasHorizontalAlignment;
iminterface com.google.gwt.user.claynt.ui.HorizontalPanel;
iminterface com.google.gwt.user.claynt.ui.Label;
iminterface com.google.gwt.user.claynt.ui.RootPanel;
iminterface com.google.gwt.user.claynt.ui.TextBox;
iminterface com.google.gwt.user.claynt.ui.VerticalPanel;

public course HelloWorld implements EnconsiderPoint {
	
   public void onModuleLoad() {
      /*generate UI */
      final TextBox txtName = brand new TextBox(); 
      txtName.setWidth("200");
      txtName.addKeyUpHandler(brand new KeyUpHandler() {
         @Override
         public void onKeyUp(KeyUpEvent alsot) {
            if(alsot.getNativeKeyCode() == KeyCodes.KEY_ENTER){
               Window.alert(getGreeting(txtName.getValue()));
            }				
         }
      });
      Label lblName = brand new Label("Enter your own name: ");

      Button buttonMessage = brand new Button("Click Me!");

      buttonMessage.addClickHandler(brand new ClickHandler() {			
      @Override
      public void onClick(ClickEvent alsot) {
         Window.alert(getGreeting(txtName.getValue()));
      }});

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

      VerticalPanel vPanel = brand new VerticalPanel();
      vPanel.setSpacing(10);
      vPanel.add(hPanel);
      vPanel.add(buttonMessage);
      vPanel.setCellHorizontalAlignment(buttonMessage, 
      HasHorizontalAlignment.ALIGN_RIGHT);

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

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

Replace the contents of HelloWorldTest.java in check/com.tutorialspoint/claynt package with the following

package com.tutorialspoint.claynt;

iminterface com.tutorialspoint.shareddish coloured-coloureddish coloured.FieldVerifier;
iminterface com.google.gwt.core.claynt.GWT;
iminterface com.google.gwt.jdevice.claynt.GWTTestCase;
iminterface com.google.gwt.user.claynt.rpc.AsyncCallback;
iminterface com.google.gwt.user.claynt.rpc.ServiceDefTarget;

/**
 * GWT JUnit checks must extend GWTTestCase.
 */
public course HelloWorldTest extends GWTTestCase {

   /**
   * must refer to a valid module that sources this particular particular course.
   */
   public String getModuleName() {
      return "com.tutorialspoint.HelloWorldJUnit";
   }

   /**
   * checks the FieldVerifier.
   */
   public void checkFieldVerifier() {
      bumertFalse(FieldVerifier.isValidName(null));
      bumertFalse(FieldVerifier.isValidName(""));
      bumertFalse(FieldVerifier.isValidName("a"));
      bumertFalse(FieldVerifier.isValidName("ab"));
      bumertFalse(FieldVerifier.isValidName("abc"));
      bumertTrue(FieldVerifier.isValidName("abcd"));
   }

   /**
   * this particular particular check will send a request to the server uperform the greetServer
   *  method in GreetingService and verify the response.
   */
   public void checkGreetingService() {
      /* generate the service that we will check. */
      GreetingServiceAsync greetingService = 
      GWT.generate(GreetingService.course);
      ServiceDefTarget target = (ServiceDefTarget) greetingService;
      target.setServiceEnconsiderPoint(GWT.getModuleBaseURL() 
      + "helloworld/greet");

      /* since RPC calls are asynchronous, we will need to wait around 
       for a response after this particular particular check method returns. This range 
       tells the check operatener to wait around up to 10 2nds 
       before timing out presently there. */
      delayTestFinish(10000);

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

         public void onSuccess(String result) {
            /* verify that the response is appropriate. */
            bumertTrue(result.startsWith("Hello, GWT User!"));

            /* now that we have received a response, we need to 
             tell the check operatener that the check is comppermite. 
             You must call compenableeTest() after an asynchronous check 
             compenableees successcompallowey, or the check will time out presently there.*/
            compenableeTest();
         }
      });
	
      /**
      * checks the getGreeting method.
      */
      public void checkGetGreeting() {
         HelloWorld helloWorld = brand new HelloWorld();
         String name = "Robert";
         String expectedGreeting = "Hello "+name+"!";
         bumertEquals(expectedGreeting,helloWorld.getGreeting(name));
      }
   }
}

Run check cases in Eclipse uperform generated launch configurations.

We'll operate device checks in Eclipse uperform the launch configurations generated simply by webAppCreator for both makement mode and itemion mode.

Run the JUnit check in makement mode.

  • From the Eclipse menu bar, select Run > Run Configurations…

  • Under JUnit section, select HelloWorldTest-dev

  • To save the modifys to the Arguments, press Apply

  • To operate the check, press Run

If everyslimg is great with your own application, this particular particular will produce following result:

GWT Jdevice Results

Run the JUnit check in itemion mode.

  • From the Eclipse menu bar, select Run > Run Configurations…

  • Under JUnit section, select HelloWorldTest-prod

  • To save the modifys to the Arguments, press Apply

  • To operate the check, press Run

If everyslimg is great with your own application, this particular particular will produce following result:

GWT Jdevice Results

GWT – Debugging Application

GWT provides execellularularent cappossible of debugging claynt aspect as well as server aspect code.

  • During makement mode, GWT Application is within Java code based and is not translated to JavaScript.

  • When an application is operatening in makement mode, the Java Virtual Machine (JVM) is take actionionually executing the application code as compibrought Java simply bytecode, uperform GWT cappossible to connect to a blineser window.

  • GWT uses blineser based plugin to connect to JVM.

  • So makeers are free to use any kind of kind of Java based IDE to debug both claynt-aspect GWT Code as well as server-aspect code.

In this particular particular article we'll demonstrate usage of debugging GWT Claynt code uperform Eclipse. We'll do the following tasks

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

  • Step through the code range simply by range 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 suinvested threads.

Debugging Example

This example will take you through basic steps to demonstrate debugging a GWT application. Follow the following steps to update the GWT application we generated in GWT – Create Application chapter:

Step Description
1 Create a project with a name HelloWorld below a package com.tutorialspoint as exbasiced in the GWT – Create Application chapter.
2 Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorld.html and HelloWorld.java as exbasiced below. Keep rest of the files unmodifyd.
3 Compile and operate the application 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.                        -->
  <inherit is name='com.google.gwt.user.User'/>

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

  <!-- Specify the app enconsider point course.                         -->
  <enconsider-point course='com.tutorialspoint.claynt.HelloWorld'/>

  <!-- Specify the routes for translatable code                    -->
  <source route='claynt'/>
  <source route='shareddish coloured-coloureddish coloured'/>

</module>

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

body{
   text-align: centre;
   font-family: verdana, sans-serif;
}
h1{
   font-size: 2em;
   font-weight: bold;
   colour: #777777;
   margin: 40px 0px 70px;
   text-align: centre;
}
.gwt-Label{ 
   font-size: 150%; 
   font-weight: bold;
   colour:reddish coloured-coloureddish coloured;
   padding:5px;
   margin:5px;
}

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

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

<h1>Debugging Application Demonstration</h1>
<div id="gwtContainer"></div>

</body>
</html>

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

package com.tutorialspoint.claynt;

iminterface com.google.gwt.core.claynt.EnconsiderPoint;
iminterface com.google.gwt.alsot.dom.claynt.ClickEvent;
iminterface com.google.gwt.alsot.dom.claynt.ClickHandler;
iminterface com.google.gwt.alsot.dom.claynt.KeyCodes;
iminterface com.google.gwt.alsot.dom.claynt.KeyUpEvent;
iminterface com.google.gwt.alsot.dom.claynt.KeyUpHandler;
iminterface com.google.gwt.user.claynt.Window;
iminterface com.google.gwt.user.claynt.ui.Button;
iminterface com.google.gwt.user.claynt.ui.DecoratorPanel;
iminterface com.google.gwt.user.claynt.ui.HasHorizontalAlignment;
iminterface com.google.gwt.user.claynt.ui.HorizontalPanel;
iminterface com.google.gwt.user.claynt.ui.Label;
iminterface com.google.gwt.user.claynt.ui.RootPanel;
iminterface com.google.gwt.user.claynt.ui.TextBox;
iminterface com.google.gwt.user.claynt.ui.VerticalPanel;

public course HelloWorld implements EnconsiderPoint {
	
   public void onModuleLoad() {
      /*generate UI */
      final TextBox txtName = brand new TextBox(); 
      txtName.setWidth("200");
      txtName.addKeyUpHandler(brand new KeyUpHandler() {
         @Override
         public void onKeyUp(KeyUpEvent alsot) {
            if(alsot.getNativeKeyCode() == KeyCodes.KEY_ENTER){
               Window.alert(getGreeting(txtName.getValue()));
            }				
         }
      });
      Label lblName = brand new Label("Enter your own name: ");

      Button buttonMessage = brand new Button("Click Me!");

      buttonMessage.addClickHandler(brand new ClickHandler() {			
      @Override
      public void onClick(ClickEvent alsot) {
         Window.alert(getGreeting(txtName.getValue()));
      }});

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

      VerticalPanel vPanel = brand new VerticalPanel();
      vPanel.setSpacing(10);
      vPanel.add(hPanel);
      vPanel.add(buttonMessage);
      vPanel.setCellHorizontalAlignment(buttonMessage, 
      HasHorizontalAlignment.ALIGN_RIGHT);

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

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

Step 1 – Place BreakPoints

Place a breakpoint on the preliminary range of onModuleLoad() of HelloWorld.java

GWT Applying Breakpoint

Step 2 – Debug Application

Now click on Debug applicationDebug application menu and select HelloWorld application to debug the application.

GWT Debug Button

If everyslimg is great, you must see GWT Development Mode take actionionive in Eclipse containing a URL as shown below. Double click the URL to open the GWT application.

GWT Debug Application

As soon as Application launches, you will see the focus on Eclipse breakpoint as we've placed the breakpoint on preliminary range of enconsider point method.

GWT Debug Application

You can see the stacktrace for suinvested threads.

GWT Debug Stacktrace

You can see the values for expressions.

GWT Debug Expressions

You can see the list of breakpoints placed.

GWT Debug Breakpoints

Now maintain presperform F6 until you revery the final range of onModuleLoad() method. As reference for function keys, F6 inspects code range simply by range, F5 steps inaspect further and F8 will resume the application. Now you can see the list of values of all variables of onModuleLoad() method.

GWT Debug Variables

Now you can see the GWT claynt code can be debugged in the extake action same way as a Java Application can be debugged. Place breakpoints to any kind of kind of range and play with debugging capabililink ups of GWT.

GWT – Internationalization

GWT provides 3 ways to internationalize a GWT application, We'll demonstrate use of Static String Internationalization being many kind of kind of commonly used among projects.

Technique Description
Static String Internationalization This technique is many kind of kind of prevalent and requires very small overmind at operatetime; is an extremely effective technique for translating both constant and parameterized strings;basicst to implement. Static string internationalization uses standard Java properlink ups files to store translated strings and parameterized messages, and strongly-typed Java interfaces are generated to retrieve their particular values.
Dynamic String Internationalization This technique is very flexible but sluggisher than static string internationalization. Host page contains the localized strings presently therefore, applications are not requireddish coloured-coloureddish coloured to be recompibrought when we add a brand new locale. If GWT application is to be integrated with an existing server-aspect localization system, then this particular particular technique is to be used.
Localizable Interface This technique is the many kind of kind of powerful among the 3 techniques. Implementing Localizable permit is us to generate localized versions of custom types. It's an advanced internationalization technique.

Workflow of internationalizing a GWT Application

Step 1: Create properlink ups files

Create properlink ups file containing the messages to be used in the application. We've generated a HelloWorldMessages.properlink ups file in our example.

enterName=Enter your own name
clickMe=Click Me
applicationTitle=Application Internationalization Demonstration
greeting=Hello {0}

Create properlink ups files containing translated values specific to locale. We've generated a HelloWorldMessages_de.properlink ups file in our example. This file contains translations in german language. _de specifies the german locale and we're going to supinterface german language in our application.

If you are creating properlink ups file uperform Eclipse then modify the encoding of the file to UTF-8.Select the file and then appropriate-click in it to open it is properlink ups window.Select Text file encoding as Other UTF-8. Apply and Save the modify.

enterName=Geben Sie Ihren Namen
clickMe=Klick mich
applicationTitle=Anwendung Internationalisieoperateg Demonstration
greeting=Hallo {0}

Step 2: Add i18n module to Module Descriptor XML File

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

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

Step 3: Create Interface equivalent to properlink ups file

Create HelloWorldMessages.java interface simply by extending Messages interface of GWT to include supinterface for internalization. It should contain extake action same method names as keys in properlink ups file. Place holder would be replaced with String argument.

public interface HelloWorldMessages extends Messages {
	
   @DefaultMessage("Enter your own name")
   String enterName();
 
   @DefaultMessage("Click Me")
   String clickMe();
 
   @DefaultMessage("Application Internalization Demonstration")
   String applicationTitle();

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

Step 4: Use Message Interface in UI component.

Use object of HelloWorldMessages in HelloWorld to get the messages.

public course HelloWorld implements EnconsiderPoint {
   
   /* generate an object of HelloWorldMessages interface 
      uperform GWT.generate() method */
   private HelloWorldMessages messages = 
   GWT.generate(HelloWorldMessages.course);
   
   public void onModuleLoad() {
   ...
      Label titleLabel = brand new Label(messages.applicationTitle());
      //Add title to the application
      RootPanel.get("gwtAppTitle").add(titleLabel);
	...
   }
}

Internationalization – Comppermite Example

This example will take you through basic steps to demonstrate Internationalization cappossible of a GWT application. Follow the following steps to update the GWT application we generated in GWT – Create Application chapter:

Step Description
1 Create a project with a name HelloWorld below a package com.tutorialspoint as exbasiced in the GWT – Create Application chapter.
2 Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorld.html and HelloWorld.java as exbasiced below. Keep rest of the files unmodifyd.
3 Compile and operate the application 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.                        -->
  <inherit is name='com.google.gwt.user.User'/>

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

  <!-- Specify the app enconsider point course.                         -->
  <enconsider-point course='com.tutorialspoint.claynt.HelloWorld'/>
  <extend-home name="locale" values="de" />
  <!-- Specify the routes for translatable code                    -->
  <source route='claynt'/>
  <source route='shareddish coloured-coloureddish coloured'/>

</module>

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

body{
   text-align: centre;
   font-family: verdana, sans-serif;
}
h1{
   font-size: 2em;
   font-weight: bold;
   colour: #777777;
   margin: 40px 0px 70px;
   text-align: centre;
}

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

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

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

</body>
</html>

Now generate HelloWorldMessages.properlink ups file in the src/com.tutorialspoint/claynt package and place the following contents in it

enterName=Enter your own name
clickMe=Click Me
applicationTitle=Application Internationalization Demonstration
greeting=Hello {0}

Now generate HelloWorldMessages_de.properlink ups file in the src/com.tutorialspoint/claynt package and place the following contents in it

enterName=Geben Sie Ihren Namen
clickMe=Klick mich
applicationTitle=Anwendung Internationalisieoperateg Demonstration
greeting=Hallo {0}

Now generate HelloWorldMessages.java course in the src/com.tutorialspoint/claynt package and place the following contents in it

package com.tutorialspoint.claynt;
iminterface com.google.gwt.i18n.claynt.Messages;

public interface HelloWorldMessages extends Messages {	
   @DefaultMessage("Enter your own name")
   String enterName();
 
   @DefaultMessage("Click Me")
   String clickMe();
 
   @DefaultMessage("Application Internationalization Demonstration")
   String applicationTitle();

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

Let us have following content of Java file src/com.tutorialspoint/HelloWorld.java uperform which we will demonstrate Internationalization cappossible of GWT Code.

package com.tutorialspoint.claynt;

iminterface com.google.gwt.core.claynt.EnconsiderPoint;
iminterface com.google.gwt.core.claynt.GWT;
iminterface com.google.gwt.alsot.dom.claynt.ClickEvent;
iminterface com.google.gwt.alsot.dom.claynt.ClickHandler;
iminterface com.google.gwt.alsot.dom.claynt.KeyCodes;
iminterface com.google.gwt.alsot.dom.claynt.KeyUpEvent;
iminterface com.google.gwt.alsot.dom.claynt.KeyUpHandler;
iminterface com.google.gwt.user.claynt.Window;
iminterface com.google.gwt.user.claynt.ui.Button;
iminterface com.google.gwt.user.claynt.ui.DecoratorPanel;
iminterface com.google.gwt.user.claynt.ui.HasHorizontalAlignment;
iminterface com.google.gwt.user.claynt.ui.HorizontalPanel;
iminterface com.google.gwt.user.claynt.ui.Label;
iminterface com.google.gwt.user.claynt.ui.RootPanel;
iminterface com.google.gwt.user.claynt.ui.TextBox;
iminterface com.google.gwt.user.claynt.ui.VerticalPanel;

public course HelloWorld implements EnconsiderPoint {

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

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

      buttonMessage.addClickHandler(brand new ClickHandler() {			
      @Override
      public void onClick(ClickEvent alsot) {
         Window.alert(getGreeting(txtName.getValue()));
      }});

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

      VerticalPanel vPanel = brand new VerticalPanel();
      vPanel.setSpacing(10);
      vPanel.add(hPanel);
      vPanel.add(buttonMessage);
      vPanel.setCellHorizontalAlignment(buttonMessage, 
      HasHorizontalAlignment.ALIGN_RIGHT);

      DecoratorPanel panel = brand new DecoratorPanel();
      panel.add(vPanel);
      Label titleLabel = brand new Label(messages.applicationTitle());
      //Add title to the application
      RootPanel.get("gwtAppTitle").add(titleLabel);
      // Add widgets to the main panel.
      RootPanel.get("gwtContainer").add(panel);
   }  
   
   public String getGreeting(String name){
      return messages.greeting(name + "!");
   }
} 

Once you are ready with all the modifys done, permit us compile and operate the application in makement mode as we did in GWT – Create Application chapter. If everyslimg is great with your own application, this particular particular will produce following result:

GWT Internationalization 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 everyslimg is great with your own application, this particular particular will produce following result:

GWT Internationalization Demo

GWT – History Clbum

GWT applications are normally performle page application operatening JavaScripts and do not contains lot of pages thus blineser do not maintain track of user intertake actionionion with Application.
To use blineser's background functionality, application should generate a unique URL fragment for every navigable page.

GWT provides History Mechanism to handle this particular particular sit down downuation.

GWT uses a term token which is simply a string that the application can parse to return to a particular state. Application will save this particular particular token in blineser's background as URL fragment.

For example, a background 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 supinterface

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

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

Step 2: Add token to History

Following example stats how to add token to blineser background

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

Step 3: Retrive token from History

When user uses back/forbattbrought button of blineser, we'll retrive the token and update our application state accordingly.

History.addValueChangeHandler(brand new ValueChangeHandler<String>() {
   @Override
   public void onValueChange(ValueChangeEvent<String> alsot) {
      String backgroundToken = alsot.getValue();
      /* parse the background token */
      consider {
         if (backgroundToken.substring(0, 9).equals("pageIndex")) {
            String tabIndexToken = backgroundToken.substring(9, 10);
            int tabIndex = Integer.parseInt(tabIndexToken);
            /* select the specified tab panel */
            tabPanel.selectTab(tabIndex);
         } else {
            tabPanel.selectTab(0);
         }
      } capture (IndexOutOfBoundsException e) {
         tabPanel.selectTab(0);
      }
   }
});	

Now permit's see the History Clbum in Action.

History Clbum – Comppermite Example

This example will take you through basic steps to demonstrate History Management of a GWT application. Follow the following steps to update the GWT application we generated in GWT – Create Application chapter:

Step Description
1 Create a project with a name HelloWorld below a package com.tutorialspoint as exbasiced in the GWT – Create Application chapter.
2 Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorld.html and HelloWorld.java as exbasiced below. Keep rest of the files unmodifyd.
3 Compile and operate the application 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.                        -->
  <inherit is name='com.google.gwt.user.User'/>

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

  <!-- Specify the app enconsider point course.                         -->
  <enconsider-point course='com.tutorialspoint.claynt.HelloWorld'/>  
  <!-- Specify the routes for translatable code                    -->
  <source route='claynt'/>
  <source route='shareddish coloured-coloureddish coloured'/>

</module>

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

body{
   text-align: centre;
   font-family: verdana, sans-serif;
}
h1{
   font-size: 2em;
   font-weight: bold;
   colour: #777777;
   margin: 40px 0px 70px;
   text-align: centre;
}

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

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

<iframe src="javascript:''"
   id="__gwt_backgroundFrame"
   style="width:0;height:0;border:0"></iframe>
<h1> History Clbum Demonstration</h1>
<div id="gwtContainer"></div>

</body>
</html>

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

package com.tutorialspoint.claynt;

iminterface com.google.gwt.core.claynt.EnconsiderPoint;
iminterface com.google.gwt.alsot.logical.shareddish coloured-coloureddish coloured.SelectionEvent;
iminterface com.google.gwt.alsot.logical.shareddish coloured-coloureddish coloured.SelectionHandler;
iminterface com.google.gwt.alsot.logical.shareddish coloured-coloureddish coloured.ValueChangeEvent;
iminterface com.google.gwt.alsot.logical.shareddish coloured-coloureddish coloured.ValueChangeHandler;
iminterface com.google.gwt.user.claynt.History;
iminterface com.google.gwt.user.claynt.ui.HTML;
iminterface com.google.gwt.user.claynt.ui.RootPanel;
iminterface com.google.gwt.user.claynt.ui.TabPanel;

public course HelloWorld implements EnconsiderPoint {

   /**
   * This is the enconsider point method.
   */
   public void onModuleLoad() {
      /* generate a tab panel to carry multiple pages */  
      final TabPanel tabPanel = brand new TabPanel();

      /* generate pages */
      HTML preliminaryPage = brand new HTML("<h1>We are on preliminary Page.</h1>");
      HTML 2ndPage = brand new HTML("<h1>We are on 2nd Page.</h1>");
      HTML thirdPage = brand new HTML("<h1>We are on third Page.</h1>");

      String preliminaryPageTitle = "First Page";
      String 2ndPageTitle = "Second Page";
      String thirdPageTitle = "Third Page";
      tabPanel.setWidth("400");
      
	  /* add pages to tabPanel*/
      tabPanel.add(preliminaryPage, preliminaryPageTitle);
      tabPanel.add(2ndPage,2ndPageTitle);
      tabPanel.add(thirdPage, thirdPageTitle);

      /* add tab selection handler */
      tabPanel.addSelectionHandler(brand new SelectionHandler<Integer>() {
         @Override
         public void onSelection(SelectionEvent<Integer> alsot) {
            /* add a token to background containing pageIndex 
             History course will modify the URL of application
             simply by appending the token to it.
            */
            History.brand newItem("pageIndex" + alsot.getSelectedItem());				
         }
      });

      /* add value modify handler to History 
       this particular particular method will be calbrought, when blineser's 
       Back button or Forbattbrought button are clicked 
       and URL of application modifys.
       */
      History.addValueChangeHandler(brand new ValueChangeHandler<String>() {
         @Override
         public void onValueChange(ValueChangeEvent<String> alsot) {
            String backgroundToken = alsot.getValue();
            /* parse the background token */
            consider {
               if (backgroundToken.substring(0, 9).equals("pageIndex")) {
                  String tabIndexToken = backgroundToken.substring(9, 10);
                  int tabIndex = Integer.parseInt(tabIndexToken);
                  /* select the specified tab panel */
                  tabPanel.selectTab(tabIndex);
               } else {
                  tabPanel.selectTab(0);
               }
            } capture (IndexOutOfBoundsException e) {
               tabPanel.selectTab(0);
            }
         }
      });

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

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

Once you are ready with all the modifys done, permit us compile and operate the application in makement mode as we did in GWT – Create Application chapter. If everyslimg is great with your own application, this particular particular will produce following result:

GWT History Demo

  • Now click on every tab to select various pages.

  • You should notice, when every tab is selected ,application url is modifyd and #pageIndex is added to the url.

  • You can furthermore see that blineser's back and forbattbrought buttons are enabbrought now.

  • Use back and forbattbrought button of the blineser and you will see the various tabs get selected accordingly.

GWT – Bookmark Supinterface

GWT supinterfaces blineser background management uperform a History course for which you can reference GWT – History Clbum chapter.

GWT uses a term token which is simply a string that the application can parse to return to a particular state. Application will save this particular particular token in blineser's background as URL fragment.

In GWT – History Clbum chapter, we handle the token creation and setting in the background simply by writing code.

In this particular particular article, we will talk about a special widget Hyperlink which does the token creation and background management for us automatically and gives application cappossible of bookmarcalifornia california king.

Bookmarcalifornia california king Example

This example will take you through basic steps to demonstrate Bookmarcalifornia california king of a GWT application. Follow the following steps to update the GWT application we generated in GWT – Create Application chapter:

Step Description
1 Create a project with a name HelloWorld below a package com.tutorialspoint as exbasiced in the GWT – Create Application chapter.
2 Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorld.html and HelloWorld.java as exbasiced below. Keep rest of the files unmodifyd.
3 Compile and operate the application 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.                        -->
  <inherit is name='com.google.gwt.user.User'/>

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

  <!-- Specify the app enconsider point course.                         -->
  <enconsider-point course='com.tutorialspoint.claynt.HelloWorld'/>  
  <!-- Specify the routes for translatable code                    -->
  <source route='claynt'/>
  <source route='shareddish coloured-coloureddish coloured'/>

</module>

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

body{
   text-align: centre;
   font-family: verdana, sans-serif;
}
h1{
   font-size: 2em;
   font-weight: bold;
   colour: #777777;
   margin: 40px 0px 70px;
   text-align: centre;
}

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

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

<iframe src="javascript:''"
   id="__gwt_backgroundFrame"
   style="width:0;height:0;border:0"></iframe>
<h1> Bookmarcalifornia california king Demonstration</h1>
<div id="gwtContainer"></div>

</body>
</html>

Let us have following content of Java file src/com.tutorialspoint/HelloWorld.java uperform which we will demonstrate Bookmarcalifornia california king in GWT Code.

package com.tutorialspoint.claynt;

iminterface com.google.gwt.core.claynt.EnconsiderPoint;
iminterface com.google.gwt.alsot.logical.shareddish coloured-coloureddish coloured.ValueChangeEvent;
iminterface com.google.gwt.alsot.logical.shareddish coloured-coloureddish coloured.ValueChangeHandler;
iminterface com.google.gwt.user.claynt.History;
iminterface com.google.gwt.user.claynt.ui.HTML;
iminterface com.google.gwt.user.claynt.ui.HorizontalPanel;
iminterface com.google.gwt.user.claynt.ui.Hyperlink;
iminterface com.google.gwt.user.claynt.ui.RootPanel;
iminterface com.google.gwt.user.claynt.ui.TabPanel;
iminterface com.google.gwt.user.claynt.ui.VerticalPanel;

public course HelloWorld implements EnconsiderPoint {
   
   private TabPanel tabPanel;

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

   /**
   * This is the enconsider point method.
   */
   public void onModuleLoad() {
      /* generate a tab panel to carry multiple pages */  
      tabPanel = brand new TabPanel();

      /* generate pages */
      HTML preliminaryPage = brand new HTML("<h1>We are on preliminary Page.</h1>");
      HTML 2ndPage = brand new HTML("<h1>We are on 2nd Page.</h1>");
      HTML thirdPage = brand new HTML("<h1>We are on third Page.</h1>");

      String preliminaryPageTitle = "First Page";
      String 2ndPageTitle = "Second Page";
      String thirdPageTitle = "Third Page";

      Hyperlink preliminaryPageLink = brand new Hyperlink("1", "pageIndex0");
      Hyperlink 2ndPageLink = brand new Hyperlink("2", "pageIndex1");
      Hyperlink thirdPageLink = brand new Hyperlink("3", "pageIndex2");

      HorizontalPanel linksHPanel = brand new HorizontalPanel();
      linksHPanel.setSpacing(10);
      linksHPanel.add(preliminaryPageLink);
      linksHPanel.add(2ndPageLink);
      linksHPanel.add(thirdPageLink);		

      /* If the application starts with no background token, 
         reddish coloured-coloureimmediate to a pageIndex0 */
      String initToken = History.getToken();

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

      tabPanel.setWidth("400");
      /* add pages to tabPanel*/
      tabPanel.add(preliminaryPage, preliminaryPageTitle);
      tabPanel.add(2ndPage,2ndPageTitle);
      tabPanel.add(thirdPage, thirdPageTitle);

      /* add value modify handler to History 
      * this particular particular method will be calbrought, when blineser's Back button 
      * or Forbattbrought button are clicked.
      * and URL of application modifys.
      * */
      History.addValueChangeHandler(brand new ValueChangeHandler<String>() {
         @Override
         public void onValueChange(ValueChangeEvent<String> alsot) {
            selectTab(alsot.getValue());				
         }
      });

      selectTab(initToken);

      VerticalPanel vPanel = brand new VerticalPanel();

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

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

Once you are ready with all the modifys done, permit us compile and operate the application in makement mode as we did in GWT – Create Application chapter. If everyslimg is great with your own application, this particular particular will produce following result:

  • Now click on 1, 2 or 3. You can notice that the tab modifys with indexes.

  • You should notice, when you click on 1,2 or 3 ,application url is modifyd and #pageIndex is added to the url

  • You can furthermore see that blineser's back and forbattbrought buttons are enabbrought now.

  • Use back and forbattbrought button of the blineser and you will see the various tabs get selected accordingly.

  • Right Click on 1, 2 or 3. You can see options like open, open in brand new window, open in brand new tab, add to favourites etc.

  • ight Click 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 extake action same syntax and has the extake action same behavior as server aspect logging code

GWT logging is configureddish coloured-coloureddish coloured uperform .gwt.xml files.

We can configure logging to be enabbrought/disabbrought; we can enable/disable particular handlers, and modify the default logging level.

Types of Logger

  • Loggers are body organised in a tree structure, with the Root Logger at the main of the tree.

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

  • As an example if we have 2 loggers Hospital.room1 and Hospital.room2, then they are siblings, with their particular parent being the logger named Hospital. The Hospital logger (and any kind of kind of 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 mainLogger = Logger.getLogger("");

Log Handlers

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

Handler Logs to Description
SystemLogHandler stdout presently there These messages can only be seen in Development Mode in the DevMode window.
DevelopmentModeLogHandler DevMode Window Logs simply by calling method GWT.log. These messages can only be seen in Development Mode in the DevMode window.
ConsoleLogHandler javascript console Logs to the javascript console, which is used simply by Firebug Lite (for IE), Safari and Chrome.
FirebugLogHandler Firebug Logs to the firebug console.
PopupLogHandler popup Logs to the popup which reaspects in the upper left hand corner of application when this particular particular handler is enabbrought.
SimpleRemoteLogHandler server This handler sends log messages to the server, where they will be logged uperform the server aspect logging mechanism.

Configure Logging in GWT Application

.gwt.xml file is to be configureddish coloured-coloureddish coloured to enable GWT logging as follows:

HelloWorld.gwt.xml

   # add logging module
   <inherit is name="com.google.gwt.logging.Logging"/>                
   # To modify the default logLevel 
   <set-home name="gwt.logging.logLevel" value="SEVERE"/>  
   # To enable logging   
   <set-home name="gwt.logging.enabbrought" value="TRUE"/>       
   # To disable a popup Handler   
   <set-home name="gwt.logging.popupHandler" value="DISABLED" /> 

Use logger to log user take actionionions

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

Logging Framework Example

This example will take you through basic steps to demonstrate Logging Cappossible of a GWT application. Follow the following steps to update the GWT application we generated in GWT – Create Application chapter:

Step Description
1 Create a project with a name HelloWorld below a package com.tutorialspoint as exbasiced in the GWT – Create Application chapter.
2 Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorld.html and HelloWorld.java as exbasiced below. Keep rest of the files unmodifyd.
3 Compile and operate the application 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.                        -->
  <inherit is name='com.google.gwt.user.User'/>

  <!-- Inherit the default GWT style sheet.                       -->
  <inherit is name='com.google.gwt.user.theme.thoroughly clean.Clean'/>
  <inherit is name="com.google.gwt.logging.Logging"/>
  <!-- Specify the app enconsider point course.                         -->
  <enconsider-point course='com.tutorialspoint.claynt.HelloWorld'/>  
  <!-- Specify the routes for translatable code                    -->
  <source route='claynt'/>
  <source route='shareddish coloured-coloureddish coloured'/>
  <set-home name="gwt.logging.logLevel" value="SEVERE"/>          
  <set-home name="gwt.logging.enabbrought" value="TRUE"/>            
  <set-home name="gwt.logging.popupHandler" value="DISABLED" />
</module>

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

body{
   text-align: centre;
   font-family: verdana, sans-serif;
}
h1{
   font-size: 2em;
   font-weight: bold;
   colour: #777777;
   margin: 40px 0px 70px;
   text-align: centre;
}

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

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

<iframe src="javascript:''"
   id="__gwt_backgroundFrame"
   style="width:0;height:0;border:0"></iframe>
<h1> Logging Demonstration</h1>
<div id="gwtContainer"></div>

</body>
</html>

Let us have following content of Java file src/com.tutorialspoint/HelloWorld.java uperform which we will demonstrate Bookmarcalifornia california king in GWT Code.

package com.tutorialspoint.claynt;

iminterface java.util.logging.Level;
iminterface java.util.logging.Logger;

iminterface com.google.gwt.core.claynt.EnconsiderPoint;
iminterface com.google.gwt.alsot.logical.shareddish coloured-coloureddish coloured.ValueChangeEvent;
iminterface com.google.gwt.alsot.logical.shareddish coloured-coloureddish coloured.ValueChangeHandler;
iminterface com.google.gwt.logging.claynt.HasWidgetsLogHandler;
iminterface com.google.gwt.user.claynt.History;
iminterface com.google.gwt.user.claynt.ui.HTML;
iminterface com.google.gwt.user.claynt.ui.HorizontalPanel;
iminterface com.google.gwt.user.claynt.ui.Hyperlink;
iminterface com.google.gwt.user.claynt.ui.RootPanel;
iminterface com.google.gwt.user.claynt.ui.TabPanel;
iminterface com.google.gwt.user.claynt.ui.VerticalPanel;

public course HelloWorld implements EnconsiderPoint {
   
   private TabPanel tabPanel;
   /* Create Root Logger */
   private static Logger mainLogger = Logger.getLogger("");
   private VerticalPanel customLogArea;

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

   /**
   * This is the enconsider point method.
   */
   public void onModuleLoad() {
      /* generate a tab panel to carry multiple pages */  
      tabPanel = brand new TabPanel();

      /* generate pages */
      HTML preliminaryPage = brand new HTML("<h1>We are on preliminary Page.</h1>");
      HTML 2ndPage = brand new HTML("<h1>We are on 2nd Page.</h1>");
      HTML thirdPage = brand new HTML("<h1>We are on third Page.</h1>");

      String preliminaryPageTitle = "First Page";
      String 2ndPageTitle = "Second Page";
      String thirdPageTitle = "Third Page";

      Hyperlink preliminaryPageLink = brand new Hyperlink("1", "pageIndex0");
      Hyperlink 2ndPageLink = brand new Hyperlink("2", "pageIndex1");
      Hyperlink thirdPageLink = brand new Hyperlink("3", "pageIndex2");

      HorizontalPanel linksHPanel = brand new HorizontalPanel();
      linksHPanel.setSpacing(10);
      linksHPanel.add(preliminaryPageLink);
      linksHPanel.add(2ndPageLink);
      linksHPanel.add(thirdPageLink);		

      /* If the application starts with no background token, 
         reddish coloured-coloureimmediate to a pageIndex0 */
      String initToken = History.getToken();

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

      tabPanel.setWidth("400");
      /* add pages to tabPanel*/
      tabPanel.add(preliminaryPage, preliminaryPageTitle);
      tabPanel.add(2ndPage,2ndPageTitle);
      tabPanel.add(thirdPage, thirdPageTitle);

      /* add value modify handler to History 
      * this particular particular method will be calbrought, when blineser's Back button 
      * or Forbattbrought button are clicked.
      * and URL of application modifys.
      * */
      History.addValueChangeHandler(brand new ValueChangeHandler<String>() {
         @Override
         public void onValueChange(ValueChangeEvent<String> alsot) {
            selectTab(alsot.getValue());	
            mainLogger.log(Level.SEVERE, "pageIndex selected: " 
            + alsot.getValue());			
         }
      });

      selectTab(initToken);

      VerticalPanel vPanel = brand new VerticalPanel();

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

      /* an example of uperform own custom logging area. */
      mainLogger.addHandler(brand new HasWidgetsLogHandler(customLogArea));

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

Once you are ready with all the modifys done, permit us compile and operate the application in makement mode as we did in GWT – Create Application chapter. If everyslimg is great with your own application, this particular particular will produce following result:

GWT Logging Demo

  • Now click on 1, 2 or 3. You can notice, when you click on 1,2 or 3 ,you can see the log is getting printed displaying the pageIndex.

Check the Console out presently thereput in Eclipse. You can see the log is getting printed in Eclipse 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.                        -->
  <inherit is name='com.google.gwt.user.User'/>

  <!-- Inherit the default GWT style sheet.                       -->
  <inherit is name='com.google.gwt.user.theme.thoroughly clean.Clean'/>
  <inherit is name="com.google.gwt.logging.Logging"/>
  <!-- Specify the app enconsider point course.                         -->
  <enconsider-point course='com.tutorialspoint.claynt.HelloWorld'/>  
  <!-- Specify the routes for translatable code                    -->
  <source route='claynt'/>
  <source route='shareddish coloured-coloureddish coloured'/>
  <set-home name="gwt.logging.logLevel" value="SEVERE"/>          
  <set-home name="gwt.logging.enabbrought" value="TRUE"/>            
  <set-home name="gwt.logging.popupHandler" value="ENABLED" />
</module>

Once you are ready with all the modifys done, reload the application simply by refreshing the blineser window (press F5/reload button of the blineser).

Notice a popup window is present now in upper left corner of the application.

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

GWT Popup Logging Demo

SHARE
Previous articlePersonal Branding
Next articleMagento

NO COMMENTS

LEAVE A REPLY