GWT – Debugging Application

GWT – Debugging Application ”; Previous Next GWT provides execellent capability of debugging client side as well as server side code. During development mode, GWT Application is in Java code based and is not translated to JavaScript. When an application is running in development mode, the Java Virtual Machine (JVM) is actually executing the application code as compiled Java bytecode, using GWT capability to connect to a browser window. GWT uses browser based plugin to connect to JVM. So developers are free to use any Java based IDE to debug both client-side GWT Code as well as server-side code. In this article we”ll demonstrate usage of debugging GWT Client code using Eclipse. We”ll do the following tasks − Set break points in the code and see them in BreakPoint Explorer. Step through the code line by line during debugging. View the values of variable. Inspect the values of all the variables. Inspect the value of an expression. Display the stack frame for suspended threads. Debugging Example This example will take you through simple steps to demonstrate debugging a GWT application. Follow the following steps to update the GWT application we created in GWT – Create Application chapter − Step Description 1 Create a project with a name HelloWorld under a package com.tutorialspoint as explained in the GWT – Create Application chapter. 2 Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorld.html and HelloWorld.java as explained below. Keep rest of the files unchanged. 3 Compile and run the 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. –> <inherits name = ”com.google.gwt.user.User”/> <!– Inherit the default GWT style sheet. –> <inherits name = ”com.google.gwt.user.theme.clean.Clean”/> <!– Specify the app entry point class. –> <entry-point class = ”com.tutorialspoint.client.HelloWorld”/> <!– Specify the paths for translatable code –> <source path = ”client”/> <source path = ”shared”/> </module> Following is the content of the modified Style Sheet file war/HelloWorld.css. body { text-align: center; font-family: verdana, sans-serif; } h1 { font-size: 2em; font-weight: bold; color: #777777; margin: 40px 0px 70px; text-align: center; } .gwt-Label{ font-size: 150%; font-weight: bold; color:red; padding:5px; margin:5px; } Following is the content of the modified HTML host file war/HelloWorld.html to accomodate two buttons. <html> <head> <title>Hello World</title> <link rel = “stylesheet” href = “HelloWorld.css”/> <script language = “javascript” src = “helloworld/helloworld.nocache.js”> </script> </head> <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 using which we will demonstrate debugging capability of GWT Code. package com.tutorialspoint.client; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.dom.client.KeyUpEvent; import com.google.gwt.event.dom.client.KeyUpHandler; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.DecoratorPanel; import com.google.gwt.user.client.ui.HasHorizontalAlignment; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.VerticalPanel; public class HelloWorld implements EntryPoint { public void onModuleLoad() { /*create UI */ final TextBox txtName = new TextBox(); txtName.setWidth(“200”); txtName.addKeyUpHandler(new KeyUpHandler() { @Override public void onKeyUp(KeyUpEvent event) { if(event.getNativeKeyCode() == KeyCodes.KEY_ENTER){ Window.alert(getGreeting(txtName.getValue())); } } }); Label lblName = new Label(“Enter your name: “); Button buttonMessage = new Button(“Click Me!”); buttonMessage.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { Window.alert(getGreeting(txtName.getValue())); }}); HorizontalPanel hPanel = new HorizontalPanel(); hPanel.add(lblName); hPanel.add(txtName); hPanel.setCellWidth(lblName, “130”); VerticalPanel vPanel = new VerticalPanel(); vPanel.setSpacing(10); vPanel.add(hPanel); vPanel.add(buttonMessage); vPanel.setCellHorizontalAlignment(buttonMessage, HasHorizontalAlignment.ALIGN_RIGHT); DecoratorPanel panel = new DecoratorPanel(); panel.add(vPanel); // Add widgets to the root panel. RootPanel.get(“gwtContainer”).add(panel); } public String getGreeting(String name){ return “Hello “+name+”!”; } } Step 1 – Place BreakPoints Place a breakpoint on the first line of onModuleLoad() of HelloWorld.java Step 2 – Debug Application Now click on Debug application menu and select HelloWorld application to debug the application. If everything is fine, you must see GWT Development Mode active in Eclipse containing a URL as shown below. Double click the URL to open the GWT application. As soon as Application launches, you will see the focus on Eclipse breakpoint as we”ve placed the breakpoint on first line of entry point method. You can see the stacktrace for suspended threads. You can see the values for expressions. You can see the list of breakpoints placed. Now keep pressing F6 until you reach the last line of onModuleLoad() method. As reference for function keys, F6 inspects code line by line, F5 steps inside further and F8 will resume the application. Now you can see the list of values of all variables of onModuleLoad() method. The GWT client code can be debugged in the same way as a Java Application can be debugged. Place breakpoints to any line and play with debugging capabilities of GWT. Print Page Previous Next Advertisements ”;

GWT – JUnit Integration

GWT – JUnit Integration ”; Previous Next GWT provides execellent support for automated testing of client side code using JUnit testing framework. In this article we”ll demonstrate GWT and JUNIT integration. Download Junit archive JUnit Official Site − https://www.junit.org Download Junit-4.10.jar OS Archive name Windows junit4.10.jar Linux junit4.10.jar Mac junit4.10.jar Store the downloaded jar file to some location on your computer. We”ve stored it at C:/ > JUNIT Locate GWT installation folder OS GWT installation folder Windows C:GWTgwt-2.1.0 Linux /usr/local/GWT/gwt-2.1.0 Mac /Library/GWT/gwt-2.1.0 GWTTestCase Class GWT provides GWTTestCase base class which provides JUnit integration. Running a compiled class which extends GWTTestCase under JUnit launches the HtmlUnit browser which serves to emulate your application behavior during test execution. GWTTestCase is a derived class from JUnit”s TestCase and it can be run using JUnit TestRunner. Using webAppCreator GWT provides a special command line tool webAppCreator which can generate a starter test case for us, plus ant targets and eclipse launch configs for testing in both development mode and production mode. Open command prompt and go to C: > GWT_WORKSPACE > where you want to create a new project with test support.Run the following command C:GWT_WORKSPACE>C:GWTgwt-2.1.0webAppCreator -out HelloWorld -junit C:JUNITjunit-4.10.jar com.tutorialspoint.HelloWorld Noteworthy Points We are executing webAppCreator command line utility. HelloWorld is the name of the project to be created -junit option instructs webAppCreator to add junit suppport to project com.tutorialspoint.HelloWorld is the name of the module Verify the output. Created directory HelloWorldsrc Created directory HelloWorldwar Created directory HelloWorldwarWEB-INF Created directory HelloWorldwarWEB-INFlib Created directory HelloWorldsrccomtutorialspoint Created directory HelloWorldsrccomtutorialspointclient Created directory HelloWorldsrccomtutorialspointserver Created directory HelloWorldsrccomtutorialspointshared Created directory HelloWorldtestcomtutorialspoint Created directory HelloWorldtestcomtutorialspointclient Created file HelloWorldsrccomtutorialspointHelloWorld.gwt.xml Created file HelloWorldwarHelloWorld.html Created file HelloWorldwarHelloWorld.css Created file HelloWorldwarWEB-INFweb.xml Created file HelloWorldsrccomtutorialspointclientHelloWorld.java Created file HelloWorldsrccomtutorialspointclientGreetingService.java Created file HelloWorldsrccomtutorialspointclientGreetingServiceAsync.java Created file HelloWorldsrccomtutorialspointserverGreetingServiceImpl.java Created file HelloWorldsrccomtutorialspointsharedFieldVerifier.java Created file HelloWorldbuild.xml Created file HelloWorldREADME.txt Created file HelloWorldtestcomtutorialspointHelloWorldJUnit.gwt.xml Created file HelloWorldtestcomtutorialspointclientHelloWorldTest.java Created file HelloWorld.project Created file HelloWorld.classpath Created file HelloWorldHelloWorld.launch Created file HelloWorldHelloWorldTest-dev.launch Created file HelloWorldHelloWorldTest-prod.launch Understanding the test class: HelloWorldTest.java package com.tutorialspoint.client; import com.tutorialspoint.shared.FieldVerifier; import com.google.gwt.core.client.GWT; import com.google.gwt.junit.client.GWTTestCase; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.rpc.ServiceDefTarget; /** * GWT JUnit tests must extend GWTTestCase. */ public class HelloWorldTest extends GWTTestCase { /** * must refer to a valid module that sources this class. */ public String getModuleName() { return “com.tutorialspoint.HelloWorldJUnit”; } /** * tests the FieldVerifier. */ public void testFieldVerifier() { assertFalse(FieldVerifier.isValidName(null)); assertFalse(FieldVerifier.isValidName(“”)); assertFalse(FieldVerifier.isValidName(“a”)); assertFalse(FieldVerifier.isValidName(“ab”)); assertFalse(FieldVerifier.isValidName(“abc”)); assertTrue(FieldVerifier.isValidName(“abcd”)); } /** * this test will send a request to the server using the greetServer * method in GreetingService and verify the response. */ public void testGreetingService() { /* create the service that we will test. */ GreetingServiceAsync greetingService = GWT.create(GreetingService.class); ServiceDefTarget target = (ServiceDefTarget) greetingService; target.setServiceEntryPoint(GWT.getModuleBaseURL() + “helloworld/greet”); /* since RPC calls are asynchronous, we will need to wait for a response after this test method returns. This line tells the test runner to wait up to 10 seconds before timing out. */ delayTestFinish(10000); /* send a request to the server. */ greetingService.greetServer(“GWT User”, new AsyncCallback<String>() { public void onFailure(Throwable caught) { /* The request resulted in an unexpected error. */ fail(“Request failure: ” + caught.getMessage()); } public void onSuccess(String result) { /* verify that the response is correct. */ assertTrue(result.startsWith(“Hello, GWT User!”)); /* now that we have received a response, we need to tell the test runner that the test is complete. You must call finishTest() after an asynchronous test finishes successfully, or the test will time out.*/ finishTest(); } }); } } Noteworthy Points Sr.No. Note 1 HelloWorldTest class was generated in the com.tutorialspoint.client package under the HelloWorld/test directory. 2 HelloWorldTest class will contain unit test cases for HelloWorld. 3 HelloWorldTest class extends the GWTTestCase class in the com.google.gwt.junit.client package. 4 HelloWorldTest class has an abstract method (getModuleName) that must return the name of the GWT module. For HelloWorld, this is com.tutorialspoint.HelloWorldJUnit. 5 HelloWorldTest class is generated with two sample test cases testFieldVerifier, testSimple. We”ve added testGreetingService. 6 These methods use one of the many assert* functions that it inherits from the JUnit Assert class, which is an ancestor of GWTTestCase. 7 The assertTrue(boolean) function asserts that the boolean argument passed in evaluates to true. If not, the test will fail when run in JUnit. GWT – JUnit Integration Complete Example This example will take you through simple steps to show example of JUnit Integration in GWT. Follow the following steps to update the GWT application we created above − Step Description 1 Import the project with a name HelloWorld in eclipse using import existing project wizard (File → Import → General → Existing Projects into workspace). 2 Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorld.html and HelloWorld.java as explained below. Keep rest of the files unchanged. 3 Compile and run the application to verify the result of the implemented logic. Following will be the project structure in eclipse. Following is the content of the modified module descriptor src/com.tutorialspoint/HelloWorld.gwt.xml. <?xml version = “1.0” encoding = “UTF-8″?> <module rename-to = ”helloworld”> <!– Inherit the core Web Toolkit stuff. –> <inherits name = ”com.google.gwt.user.User”/> <!– Inherit the default GWT style sheet. –> <inherits name = ”com.google.gwt.user.theme.clean.Clean”/> <!– Inherit the UiBinder module. –> <inherits name = “com.google.gwt.uibinder.UiBinder”/> <!– Specify the app entry point class. –> <entry-point class = ”com.tutorialspoint.client.HelloWorld”/> <!– Specify the paths for translatable code –> <source path = ”client”/> <source path = ”shared”/> </module> Following is the content of the modified Style Sheet file war/HelloWorld.css. body { text-align: center; font-family: verdana, sans-serif; } h1 { font-size: 2em; font-weight: bold; color: #777777; margin: 40px 0px 70px; text-align: center; } Following is the content of the modified HTML host file war/HelloWorld.html. <html> <head> <title>Hello World</title> <link rel = “stylesheet” href = “HelloWorld.css”/> <script language = “javascript” src = “helloworld/helloworld.nocache.js”> </script> </head> <body> <h1>JUnit Integration Demonstration</h1> <div id = “gwtContainer”></div> </body> </html> Replace the contents of HelloWorld.java in src/com.tutorialspoint/client package with the following package com.tutorialspoint.client; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.dom.client.KeyUpEvent; import com.google.gwt.event.dom.client.KeyUpHandler; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.DecoratorPanel; import com.google.gwt.user.client.ui.HasHorizontalAlignment; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.VerticalPanel; public class HelloWorld implements

GWT – Quick Guide

GWT – Quick Guide ”; Previous Next GWT – Overview What is GWT? Google Web Toolkit (GWT) is a development toolkit to create RICH Internet Applications (RIA). Here are some of its notable features − GWT provides developers option to write client side application in JAVA. GWT compiles the code written in JAVA to JavaScript code. Application written in GWT is cross-browser compliant. GWT automatically generates javascript code suitable for each browser. GWT is open source, completely free, and used by thousands of developers around the world. It is licensed under the Apache License version 2.0. Overall, GWT is a framework to build large scale and high performance web appliation while keeping them as easy-to-maintain. Why to use GWT? Being Java based, you can use JAVA IDEs like Eclipse to develop a GWT application. Developers can use code auto-complete/refactoring/navigation/project management and all features of IDEs.GWT which provides full debugging capability. Developers can debug the client side application just as a Java Application. GWT provides easy integration with Junit and Maven. Again being Java based, GWT has a low learning curve for Java Developers. GWT generates optimized javascript code, produces browser”s specific javascript code by self. GWT provides Widgets library provides most of tasks required in an application. GWT is extensible and custom widget can be created to cater to application needs. On top of everything, GWT applications can run on all major browsers and smart phones including Android and iOS based phones/tablets. Disadvantages of GWT Although GWT offers plenty of advantages, it suffers from the following disadvantages − Not Indexable − Web pages generated by GWT would not be indexed by search engines because these applications are generated dynamically. Not Degradable − If your application user disables Javascript then user will just see the basic page and nothing more. Not Designer”s Friendly − GWT is not suitable for web designers who prefer using plain HTML with placeholders for inserting dynamic content at later point in time. The GWT Components The GWT framework can be divided into following three major parts − GWT Java to JavaScript compiler − This is the most important part of GWT which makes it a powerful tool for building RIAs. The GWT compiler is used to translate all the application code written in Java into JavaScript. JRE Emulation library − Google Web Toolkit includes a library that emulates a subset of the Java runtime library. The list includes java.lang, java.lang.annotation, java.math, java.io, java.sql, java.util and java.util.logging GWT UI building library − This part of GWT consists of many subparts which includes the actual UI components, RPC support, History management, and much more. GWT also provides a GWT Hosted Web Browser which lets you run and execute your GWT applications in hosted mode, where your code runs as Java in the Java Virtual Machine without compiling to JavaScript. GWT – Environment Setup This tutorial will guide you on how to prepare a development environment to start your work with GWT Framework. This tutorial will also teach you how to setup JDK, Tomcat and Eclipse on your machine before you setup GWT Framework − System Requirement GWT requires JDK 1.6 or higher so the very first requirement is to have JDK installed in your machine. JDK 1.6 or above. Memory no minimum requirement. Disk Space no minimum requirement. Operating System no minimum requirement. Follow the given steps to setup your environment to start with GWT application development. Step 1 – Verify Java Installation on your Machine Now open console and execute the following java command. OS Task Command Windows Open Command Console c:> java -version Linux Open Command Terminal $ java -version Mac Open Terminal machine:~ joseph$ java -version Let”s verify the output for all the operating systems Sr.No. OS & Generated Output 1 Windows java version “1.6.0_21” Java(TM) SE Runtime Environment (build 1.6.0_21-b07) Java HotSpot(TM) Client VM (build 17.0-b17, mixed mode, sharing) 2 Linux java version “1.6.0_21” Java(TM) SE Runtime Environment (build 1.6.0_21-b07) ava HotSpot(TM) Client VM (build 17.0-b17, mixed mode, sharing) 3 Mac java version “1.6.0_21” Java(TM) SE Runtime Environment (build 1.6.0_21-b07) Java HotSpot(TM)64-Bit Server VM (build 17.0-b17, mixed mode, sharing) Step 2 – Setup Java Development Kit (JDK) If you do not have Java installed then you can install the Java Software Development Kit (SDK) from Oracle”s Java site: Java SE Downloads. You will find instructions for 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 directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively. Set the JAVA_HOME environment variable to point to the base directory location where Java is installed on your machine. For example Sr.No. OS & Output 1 Windows Set the environment variable JAVA_HOME to C:Program FilesJavajdk1.6.0_21 2 Linux export JAVA_HOME = /usr/local/java-current 3 Mac export JAVA_HOME = /Library/Java/Home Append Java compiler location to System Path. Sr.No. OS & Output 1 Windows Append the string ;%JAVA_HOME%bin to the end of the system variable, Path. 2 Linux export PATH=$PATH:$JAVA_HOME/bin/ 3 Mac not required Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, compile and run a simple program to confirm that the IDE knows where you installed Java, otherwise do proper setup as given document of the IDE. Step 3 – Setup Eclipse IDE All the examples in this tutorial have been written using Eclipse IDE. So I would suggest you should have latest version of Eclipse installed on your machine based on your operating system. To install Eclipse IDE, download the latest Eclipse binaries from https://www.eclipse.org. 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 by executing the following commands on windows machine, or you can simply double click on eclipse.exe %C:eclipseeclipse.exe Eclipse can be started by executing the following commands on Unix (Solaris, Linux,

GWT – Bookmark Support

GWT – Bookmark Support ”; Previous Next GWT supports browser history management using a History class for which you can reference GWT – History Class chapter. GWT uses a term token which is simply a string that the application can parse to return to a particular state. Application will save this token in browser”s history as URL fragment. In GWT – History Class chapter, we handle the token creation and setting in the history by writing code. In this article, we will discuss a special widget Hyperlink which does the token creation and history management for us automatically and gives application capability of bookmarking. Bookmarking Example This example will take you through simple steps to demonstrate Bookmarking of a GWT application. The following steps to update the GWT application we created in GWT – Create Application chapter − Step Description 1 Create a project with a name HelloWorld under a package com.tutorialspoint as explained in the GWT – Create Application chapter. 2 Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorld.html and HelloWorld.java as explained below. Keep rest of the files unchanged. 3 Compile and run the 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. –> <inherits name = ”com.google.gwt.user.User”/> <!– Inherit the default GWT style sheet. –> <inherits name = ”com.google.gwt.user.theme.clean.Clean”/> <!– Specify the app entry point class. –> <entry-point class = ”com.tutorialspoint.client.HelloWorld”/> <!– Specify the paths for translatable code –> <source path = ”client”/> <source path = ”shared”/> </module> Following is the content of the modified Style Sheet file war/HelloWorld.css. body { text-align: center; font-family: verdana, sans-serif; } h1 { font-size: 2em; font-weight: bold; color: #777777; margin: 40px 0px 70px; text-align: center; } Following is the content of the modified HTML host file war/HelloWorld.html <html> <head> <title>Hello World</title> <link rel = “stylesheet” href = “HelloWorld.css”/> <script language = “javascript” src = “helloworld/helloworld.nocache.js”> </script> </head> <body> <iframe src = “javascript:”””id = “__gwt_historyFrame” style = “width:0;height:0;border:0”></iframe> <h1> Bookmarking Demonstration</h1> <div id = “gwtContainer”></div> </body> </html> Let us have following content of Java file src/com.tutorialspoint/HelloWorld.java using which we will demonstrate Bookmarking in GWT Code. package com.tutorialspoint.client; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.user.client.History; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Hyperlink; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.TabPanel; import com.google.gwt.user.client.ui.VerticalPanel; public class HelloWorld implements EntryPoint { private TabPanel tabPanel; private void selectTab(String historyToken){ /* parse the history token */ try { if (historyToken.substring(0, 9).equals(“pageIndex”)) { String tabIndexToken = historyToken.substring(9, 10); int tabIndex = Integer.parseInt(tabIndexToken); /* Select the specified tab panel */ tabPanel.selectTab(tabIndex); } else { tabPanel.selectTab(0); } } catch (IndexOutOfBoundsException e) { tabPanel.selectTab(0); } } /** * This is the entry point method. */ public void onModuleLoad() { /* create a tab panel to carry multiple pages */ tabPanel = new TabPanel(); /* create pages */ HTML firstPage = new HTML(“<h1>We are on first Page.</h1>”); HTML secondPage = new HTML(“<h1>We are on second Page.</h1>”); HTML thirdPage = new HTML(“<h1>We are on third Page.</h1>”); String firstPageTitle = “First Page”; String secondPageTitle = “Second Page”; String thirdPageTitle = “Third Page”; Hyperlink firstPageLink = new Hyperlink(“1”, “pageIndex0”); Hyperlink secondPageLink = new Hyperlink(“2”, “pageIndex1”); Hyperlink thirdPageLink = new Hyperlink(“3”, “pageIndex2”); HorizontalPanel linksHPanel = new HorizontalPanel(); linksHPanel.setSpacing(10); linksHPanel.add(firstPageLink); linksHPanel.add(secondPageLink); linksHPanel.add(thirdPageLink); /* If the application starts with no history token, redirect to a pageIndex0 */ String initToken = History.getToken(); if (initToken.length() == 0) { History.newItem(“pageIndex0”); initToken = “pageIndex0”; } tabPanel.setWidth(“400″); /* add pages to tabPanel*/ tabPanel.add(firstPage, firstPageTitle); tabPanel.add(secondPage,secondPageTitle); tabPanel.add(thirdPage, thirdPageTitle); /* add value change handler to History * this method will be called, when browser”s Back button * or Forward button are clicked. * and URL of application changes. * */ History.addValueChangeHandler(new ValueChangeHandler<String>() { @Override public void onValueChange(ValueChangeEvent<String> event) { selectTab(event.getValue()); } }); selectTab(initToken); VerticalPanel vPanel = new VerticalPanel(); vPanel.setSpacing(10); vPanel.add(tabPanel); vPanel.add(linksHPanel); /* add controls to RootPanel */ RootPanel.get().add(vPanel); } } Once you are ready with all the changes done, let us compile and run the application in development mode as we did in GWT – Create Application chapter. If everything is fine with your application, this will produce following result − Now click on 1, 2 or 3. You can notice that the tab changes with indexes. You should notice, when you click on 1,2 or 3 ,application url is changed and #pageIndex is added to the url You can also see that browser”s back and forward buttons are enabled now. Use back and forward button of the browser and you will see the different tabs get selected accordingly. Right Click on 1, 2 or 3. You can see options like open, open in new window, open in new tab, add to favourites etc. Right 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. Print Page Previous Next Advertisements ”;

GWT – History Class

GWT – History Class ”; Previous Next GWT applications are normally single page application running JavaScripts and do not contains lot of pages thus browser do not keep track of user interaction with Application. To use browser”s history functionality, application should generate a unique URL fragment for each navigable page. GWT provides History Mechanism to handle this situation. GWT uses a term token which is simply a string that the application can parse to return to a particular state. Application will save this token in browser”s history as URL fragment. For example, a history token named “pageIndex1” would be added to a URL as follows − http://www.tutorialspoint.com/HelloWorld.html#pageIndex0 History Management Workflow Step 1 – Enable History support In order to use GWT History support, we must first embed following iframe into our host HTML page. <iframe src = “javascript:””” id = “__gwt_historyFrame” style = “width:0;height:0;border:0”></iframe> Step 2 – Add token to History Following example stats how to add token to browser history int index = 0; History.newItem(“pageIndex” + index); Step 3 – Retrive token from History When user uses back/forward button of browser, we”ll retrive the token and update our application state accordingly. History.addValueChangeHandler(new ValueChangeHandler<String>() { @Override public void onValueChange(ValueChangeEvent<String> event) { String historyToken = event.getValue(); /* parse the history token */ try { if (historyToken.substring(0, 9).equals(“pageIndex”)) { String tabIndexToken = historyToken.substring(9, 10); int tabIndex = Integer.parseInt(tabIndexToken); /* select the specified tab panel */ tabPanel.selectTab(tabIndex); } else { tabPanel.selectTab(0); } } catch (IndexOutOfBoundsException e) { tabPanel.selectTab(0); } } }); Now let”s see the History Class in Action. History Class – Complete Example This example will take you through simple steps to demonstrate History Management of a GWT application. Follow the following steps to update the GWT application we created in GWT – Create Application chapter − Step Description 1 Create a project with a name HelloWorld under a package com.tutorialspoint as explained in the GWT – Create Application chapter. 2 Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorld.html and HelloWorld.java as explained below. Keep rest of the files unchanged. 3 Compile and run the 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. –> <inherits name = ”com.google.gwt.user.User”/> <!– Inherit the default GWT style sheet. –> <inherits name = ”com.google.gwt.user.theme.clean.Clean”/> <!– Specify the app entry point class. –> <entry-point class = ”com.tutorialspoint.client.HelloWorld”/> <!– Specify the paths for translatable code –> <source path = ”client”/> <source path = ”shared”/> </module> Following is the content of the modified Style Sheet file war/HelloWorld.css. body { text-align: center; font-family: verdana, sans-serif; } h1 { font-size: 2em; font-weight: bold; color: #777777; margin: 40px 0px 70px; text-align: center; } Following is the content of the modified HTML host file war/HelloWorld.html <html> <head> <title>Hello World</title> <link rel = “stylesheet” href = “HelloWorld.css”/> <script language = “javascript” src = “helloworld/helloworld.nocache.js”> </script> </head> <body> <iframe src = “javascript:”””id = “__gwt_historyFrame” style = “width:0;height:0;border:0”></iframe> <h1> History Class Demonstration</h1> <div id = “gwtContainer”></div> </body> </html> Let us have following content of Java file src/com.tutorialspoint/HelloWorld.java using which we will demonstrate History Management in GWT Code. package com.tutorialspoint.client; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.event.logical.shared.SelectionEvent; import com.google.gwt.event.logical.shared.SelectionHandler; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.user.client.History; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.TabPanel; public class HelloWorld implements EntryPoint { /** * This is the entry point method. */ public void onModuleLoad() { /* create a tab panel to carry multiple pages */ final TabPanel tabPanel = new TabPanel(); /* create pages */ HTML firstPage = new HTML(“<h1>We are on first Page.</h1>”); HTML secondPage = new HTML(“<h1>We are on second Page.</h1>”); HTML thirdPage = new HTML(“<h1>We are on third Page.</h1>”); String firstPageTitle = “First Page”; String secondPageTitle = “Second Page”; String thirdPageTitle = “Third Page”; tabPanel.setWidth(“400”); /* add pages to tabPanel*/ tabPanel.add(firstPage, firstPageTitle); tabPanel.add(secondPage,secondPageTitle); tabPanel.add(thirdPage, thirdPageTitle); /* add tab selection handler */ tabPanel.addSelectionHandler(new SelectionHandler<Integer>() { @Override public void onSelection(SelectionEvent<Integer> event) { /* add a token to history containing pageIndex History class will change the URL of application by appending the token to it. */ History.newItem(“pageIndex” + event.getSelectedItem()); } }); /* add value change handler to History this method will be called, when browser”s Back button or Forward button are clicked and URL of application changes. */ History.addValueChangeHandler(new ValueChangeHandler<String>() { @Override public void onValueChange(ValueChangeEvent<String> event) { String historyToken = event.getValue(); /* parse the history token */ try { if (historyToken.substring(0, 9).equals(“pageIndex”)) { String tabIndexToken = historyToken.substring(9, 10); int tabIndex = Integer.parseInt(tabIndexToken); /* select the specified tab panel */ tabPanel.selectTab(tabIndex); } else { tabPanel.selectTab(0); } } catch (IndexOutOfBoundsException e) { tabPanel.selectTab(0); } } }); /* select the first tab by default */ tabPanel.selectTab(0); /* add controls to RootPanel */ RootPanel.get().add(tabPanel); } } Once you are ready with all the changes done, let us compile and run the application in development mode as we did in GWT – Create Application chapter. If everything is fine with your application, this will produce following result − Now click on each tab to select different pages. You should notice, when each tab is selected ,application url is changed and #pageIndex is added to the url. You can also see that browser”s back and forward buttons are enabled now. Use back and forward button of the browser and you will see the different tabs get selected accordingly. Print Page Previous Next Advertisements ”;

GWT – Event Handling

GWT – Event Handling ”; Previous Next GWT provides a event handler model similar to Java AWT or SWING User Interface frameworks. A listener interface defines one or more methods that the widget calls to announce an event. GWT provides a list of interfaces corresponding to various possible events. A class wishing to receive events of a particular type implements the associated handler interface and then passes a reference to itself to the widget to subscribe to a set of events. For example, the Button class publishes click events so you will have to write a class to implement ClickHandler to handle click event. Event Handler Interfaces All GWT event handlers have been extended from EventHandler interface and each handler has only a single method with a single argument. This argument is always an object of associated event type. Each event object have a number of methods to manipulate the passed event object. For example for click event you will have to write your handler as follows − /** * create a custom click handler which will call * onClick method when button is clicked. */ public class MyClickHandler implements ClickHandler { @Override public void onClick(ClickEvent event) { Window.alert(“Hello World!”); } } Now any class wishing to receive click events will call addClickHandler() to register an event handler as follows − /** * create button and attach click handler */ Button button = new Button(“Click Me!”); button.addClickHandler(new MyClickHandler()); Each widget supporting an event type will have a method of the form HandlerRegistration addFooHandler(FooEvent) where Foo is the actual event like Click, Error, KeyPress etc. Following is the list of important GWT event handlers and associated events and handler registration methods − Sr.No. Event Interface Event Method & Description 1 Before Selection Handler<I> void on Before Selection (Before Selection Event<I> event); Called when BeforeSelectionEvent is fired. 2 BlurHandler void on Blur(Blur Event event); Called when Blur Event is fired. 3 ChangeHandler void on Change(ChangeEvent event); Called when a change event is fired. 4 ClickHandler void on Click(ClickEvent event); Called when a native click event is fired. 5 CloseHandler<T> void on Close(CloseEvent<T> event); Called when CloseEvent is fired. 6 Context Menu Handler void on Context Menu(Context Menu Event event); Called when a native context menu event is fired. 7 Double Click Handler void on Double Click(Double Click Event event); Called when a Double Click Event is fired. 8 Error Handler void on Error(Error Event event); Called when Error Event is fired. 9 Focus Handler void on Focus(Focus Event event); Called when Focus Event is fired. 10 Form Panel.Submit Complete Handler void on Submit Complete(Form Panel.Submit Complete Event event); Fired when a form has been submitted successfully. 11 FormPanel.SubmitHandler void on Submit(Form Panel.Submit Event event); Fired when the form is submitted. 12 Key Down Handler void on Key Down(Key Down Event event); Called when KeyDownEvent is fired. 13 KeyPressHandler void on KeyPress(KeyPressEvent event); Called when KeyPressEvent is fired. 14 KeyUpHandler void on KeyUp(KeyUpEvent event); Called when KeyUpEvent is fired. 15 LoadHandler void on Load(LoadEvent event); Called when LoadEvent is fired. 16 MouseDownHandler void on MouseDown(MouseDownEvent event); Called when MouseDown is fired. 17 MouseMoveHandler void on MouseMove(MouseMoveEvent event); Called when MouseMoveEvent is fired. 18 MouseOutHandler void on MouseOut(MouseOutEvent event); Called when MouseOutEvent is fired. 19 MouseOverHandler void on MouseOver(MouseOverEvent event); Called when MouseOverEvent is fired. 20 MouseUpHandler void on MouseUp(MouseUpEvent event); Called when MouseUpEvent is fired. 21 MouseWheelHandler void on MouseWheel(MouseWheelEvent event); Called when MouseWheelEvent is fired. 22 ResizeHandler void on Resize(ResizeEvent event); Fired when the widget is resized. 23 ScrollHandler void on Scroll(ScrollEvent event); Called when ScrollEvent is fired. 24 SelectionHandler<I> void on Selection(SelectionEvent<I> event); Called when SelectionEvent is fired. 25 ValueChangeHandler<I> void on ValueChange(ValueChangeEvent<I> event); Called when ValueChangeEvent is fired. 26 Window.ClosingHandler void on WindowClosing(Window.ClosingEvent event); Fired just before the browser window closes or navigates to a different site. 27 Window.ScrollHandler void on WindowScroll(Window.ScrollEvent event); Fired when the browser window is scrolled. Event Methods As mentioned earlier, each handler has a single method with a single argument which holds the event object, for example void onClick(ClickEvent event) or void onKeyDown(KeyDownEvent event). The event objects like ClickEvent and KeyDownEvent has few common methods which are listed below − Sr.No. Method & Description 1 protected void dispatch(ClickHandler handler) This method Should only be called by HandlerManager 2 DomEvent.Type <FooHandler> getAssociatedType() This method returns the type used to register Foo event. 3 static DomEvent.Type<FooHandler> getType() This method gets the event type associated with Foo events. 4 public java.lang.Object getSource() This method returns the source that last fired this event. 5 protected final boolean isLive() This method returns whether the event is live. 6 protected void kill() This method kills the event Example This example will take you through simple steps to show usage of a Click Event and KeyDown Event handling in GWT. Follow the following steps to update the GWT application we created in GWT – Create Application chapter − Step Description 1 Create a project with a name HelloWorld under a package com.tutorialspoint as explained in the GWT – Create Application chapter. 2 Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorld.html and HelloWorld.java as explained below. Keep rest of the files unchanged. 3 Compile and run the 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. –> <inherits name = ”com.google.gwt.user.User”/> <!– Inherit the default GWT style sheet. –> <inherits name = ”com.google.gwt.user.theme.clean.Clean”/> <!– Specify the app entry point class. –> <entry-point class = ”com.tutorialspoint.client.HelloWorld”/> <!– Specify the paths for translatable code –> <source path = ”client”/> <source path = ”shared”/> </module> Following is the content of the modified Style Sheet file war/HelloWorld.css. body { text-align: center; font-family: verdana, sans-serif; } h1 { font-size: 2em; font-weight: bold; color: #777777; margin: 40px 0px 70px; text-align: center; } Following is the content of the modified HTML host file war/HelloWorld.html. <html> <head> <title>Hello World</title> <link rel = “stylesheet”

GWT – Logging Framework

GWT – Logging Framework ”; Previous Next The logging framework emulates java.util.logging, so it uses the same syntax and has the same behavior as server side logging code GWT logging is configured using .gwt.xml files. We can configure logging to be enabled/disabled; we can enable/disable particular handlers, and change the default logging level. Types of Logger Loggers are organized in a tree structure, with the Root Logger at the root of the tree. Name of the logger determine the Parent/Child relationships using . to separate sections of the name. As an example if we have two loggers Hospital.room1 and Hospital.room2, then they are siblings, with their parent being the logger named Hospital. The Hospital logger (and any logger with a name which does not contain a dot “.”) has the Root Logger as a parent. private static Logger room1Logger = Logger.getLogger(“Hospital.room1”); private static Logger room2Logger = Logger.getLogger(“Hospital.room2”); private static Logger hospitalLogger = Logger.getLogger(“Hospital”); private static Logger rootLogger = Logger.getLogger(“”); Log Handlers GWT provides default handlers which will show the log entries made using loggers. Handler Logs to Description SystemLogHandler stdout These messages can only be seen in Development Mode in the DevMode window. DevelopmentModeLogHandler DevMode Window Logs 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 by Firebug Lite (for IE), Safari and Chrome. FirebugLogHandler Firebug Logs to the firebug console. PopupLogHandler popup Logs to the popup which resides in the upper left hand corner of application when this handler is enabled. SimpleRemoteLogHandler server This handler sends log messages to the server, where they will be logged using the server side logging mechanism. Configure Logging in GWT Application HelloWorld.gwt.xml file is to be configured to enable GWT logging as follows − # add logging module <inherits name = “com.google.gwt.logging.Logging”/> # To change the default logLevel <set-property name = “gwt.logging.logLevel” value = “SEVERE”/> # To enable logging <set-property name = “gwt.logging.enabled” value = “TRUE”/> # To disable a popup Handler <set-property name = “gwt.logging.popupHandler” value = “DISABLED” /> Use logger to log user actions /* Create Root Logger */ private static Logger rootLogger = Logger.getLogger(“”); … rootLogger.log(Level.SEVERE, “pageIndex selected: ” + event.getValue()); … Logging Framework Example This example will take you through simple steps to demonstrate Logging Capability of a GWT application. Follow the following steps to update the GWT application we created in GWT – Create Application chapter − Step Description 1 Create a project with a name HelloWorld under a package com.tutorialspoint as explained in the GWT – Create Application chapter. 2 Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorld.html and HelloWorld.java as explained below. Keep rest of the files unchanged. 3 Compile and run the 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. –> <inherits name = ”com.google.gwt.user.User”/> <!– Inherit the default GWT style sheet. –> <inherits name = ”com.google.gwt.user.theme.clean.Clean”/> <inherits name = “com.google.gwt.logging.Logging”/> <!– Specify the app entry point class. –> <entry-point class = ”com.tutorialspoint.client.HelloWorld”/> <!– Specify the paths for translatable code –> <source path = ”client”/> <source path = ”shared”/> <set-property name = “gwt.logging.logLevel” value=”SEVERE”/> <set-property name = “gwt.logging.enabled” value = “TRUE”/> <set-property name = “gwt.logging.popupHandler” value= “DISABLED” /> </module> Following is the content of the modified Style Sheet file war/HelloWorld.css. body { text-align: center; font-family: verdana, sans-serif; } h1 { font-size: 2em; font-weight: bold; color: #777777; margin: 40px 0px 70px; text-align: center; } Following is the content of the modified HTML host file war/HelloWorld.html <html> <head> <title>Hello World</title> <link rel = “stylesheet” href = “HelloWorld.css”/> <script language = “javascript” src = “helloworld/helloworld.nocache.js”> </script> </head> <body> <iframe src = “javascript:”””id = “__gwt_historyFrame” style = “width:0;height:0;border:0”></iframe> <h1> Logging Demonstration</h1> <div id = “gwtContainer”></div> </body> </html> Let us have following content of Java file src/com.tutorialspoint/HelloWorld.java using which we will demonstrate Bookmarking in GWT Code. package com.tutorialspoint.client; import java.util.logging.Level; import java.util.logging.Logger; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.logging.client.HasWidgetsLogHandler; import com.google.gwt.user.client.History; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Hyperlink; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.TabPanel; import com.google.gwt.user.client.ui.VerticalPanel; public class HelloWorld implements EntryPoint { private TabPanel tabPanel; /* Create Root Logger */ private static Logger rootLogger = Logger.getLogger(“”); private VerticalPanel customLogArea; private void selectTab(String historyToken){ /* parse the history token */ try { if (historyToken.substring(0, 9).equals(“pageIndex”)) { String tabIndexToken = historyToken.substring(9, 10); int tabIndex = Integer.parseInt(tabIndexToken); /* Select the specified tab panel */ tabPanel.selectTab(tabIndex); } else { tabPanel.selectTab(0); } } catch (IndexOutOfBoundsException e) { tabPanel.selectTab(0); } } /** * This is the entry point method. */ public void onModuleLoad() { /* create a tab panel to carry multiple pages */ tabPanel = new TabPanel(); /* create pages */ HTML firstPage = new HTML(“<h1>We are on first Page.</h1>”); HTML secondPage = new HTML(“<h1>We are on second Page.</h1>”); HTML thirdPage = new HTML(“<h1>We are on third Page.</h1>”); String firstPageTitle = “First Page”; String secondPageTitle = “Second Page”; String thirdPageTitle = “Third Page”; Hyperlink firstPageLink = new Hyperlink(“1”, “pageIndex0”); Hyperlink secondPageLink = new Hyperlink(“2”, “pageIndex1”); Hyperlink thirdPageLink = new Hyperlink(“3”, “pageIndex2”); HorizontalPanel linksHPanel = new HorizontalPanel(); linksHPanel.setSpacing(10); linksHPanel.add(firstPageLink); linksHPanel.add(secondPageLink); linksHPanel.add(thirdPageLink); /* If the application starts with no history token, redirect to a pageIndex0 */ String initToken = History.getToken(); if (initToken.length() == 0) { History.newItem(“pageIndex0”); initToken = “pageIndex0”; } tabPanel.setWidth(“400″); /* add pages to tabPanel*/ tabPanel.add(firstPage, firstPageTitle); tabPanel.add(secondPage,secondPageTitle); tabPanel.add(thirdPage, thirdPageTitle); /* add value change handler to History * this method will be called, when browser”s Back button * or Forward button are clicked. * and URL of application changes. * */ History.addValueChangeHandler(new ValueChangeHandler<String>() { @Override public void onValueChange(ValueChangeEvent<String> event) { selectTab(event.getValue()); rootLogger.log(Level.SEVERE, “pageIndex selected: ” + event.getValue()); } }); selectTab(initToken); VerticalPanel vPanel = new VerticalPanel(); vPanel.setSpacing(10); vPanel.add(tabPanel); vPanel.add(linksHPanel); customLogArea = new VerticalPanel(); vPanel.add(customLogArea); /* an example of using own custom logging area. */ rootLogger.addHandler(new HasWidgetsLogHandler(customLogArea)); /* add controls to RootPanel */ RootPanel.get().add(vPanel); } } Once you are ready with all the changes done, let us compile and run the application

GWT – Form Widgets

GWT – Form Widgets ”; Previous Next Form widgets allows users to input data and provides them interaction capability with the application. Every Form widget inherits properties from Widget class which in turn inherits properties from UIObject and Wigdet classes. Sr.No. Widget & Description 1 GWT UIObject Class This widget contains text, not interpreted as HTML using a <div>element, causing it to be displayed with block layout. 2 GWT Widget Class This widget can contain HTML text and displays the html content using a <div> element, causing it to be displayed with block layout. Form Widgets Following are few important Form Widgets − Sr.No. Widget & Description 1 Button This widget represents a standard push button. 2 PushButton This widget represents a normal push button with custom styling. 3 ToggleButton This widget represents a stylish stateful button which allows the user to toggle between up and down states. 4 CheckBox This widget represents a standard check box widget. This class also serves as a base class for RadioButton. 5 RadioButton This widget represents a mutually-exclusive selection radio button widget. 6 ListBox This widget represents a list of choices to the user, either as a list box or as a drop-down list. 7 SuggestBox This widget represents a text box or text area which displays a pre-configured set of selections that match the user”s input. Each SuggestBox is associated with a single SuggestOracle. The SuggestOracle is used to provide a set of selections given a specific query string. 8 TextBox This widget represents a single line text box. 9 PasswordTextBox This widget represents a text box that visually masks its input to prevent eavesdropping.. 10 TextArea This widget represents a text box that allows multiple lines of text to be entered. 11 RichTextArea This widget represents a rich text editor that allows 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. Print Page Previous Next Advertisements ”;

GWT – Environment Setup

GWT – Environment Setup ”; Previous Next This tutorial will guide you on how to prepare a development environment to start your work with GWT Framework. This tutorial will also teach you how to setup JDK, Tomcat and Eclipse on your machine before you setup GWT Framework − System Requirement GWT requires JDK 1.6 or higher so the very first requirement is to have JDK installed in your machine. JDK 1.6 or above. Memory no minimum requirement. Disk Space no minimum requirement. Operating System no minimum requirement. Follow the given steps to setup your environment to start with GWT application development. Step 1 – Verify Java Installation on your Machine Now open console and execute the following java command. OS Task Command Windows Open Command Console c:> java -version Linux Open Command Terminal $ java -version Mac Open Terminal machine:~ joseph$ java -version Let”s verify the output for all the operating systems Sr.No. OS & Generated Output 1 Windows java version “1.6.0_21” Java(TM) SE Runtime Environment (build 1.6.0_21-b07) Java HotSpot(TM) Client VM (build 17.0-b17, mixed mode, sharing) 2 Linux java version “1.6.0_21” Java(TM) SE Runtime Environment (build 1.6.0_21-b07) ava HotSpot(TM) Client VM (build 17.0-b17, mixed mode, sharing) 3 Mac java version “1.6.0_21” Java(TM) SE Runtime Environment (build 1.6.0_21-b07) Java HotSpot(TM)64-Bit Server VM (build 17.0-b17, mixed mode, sharing) Step 2 – Setup Java Development Kit (JDK) If you do not have Java installed then you can install the Java Software Development Kit (SDK) from Oracle”s Java site: Java SE Downloads. You will find instructions for 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 directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively. Set the JAVA_HOME environment variable to point to the base directory location where Java is installed on your machine. For example Sr.No. OS & Output 1 Windows Set the environment variable JAVA_HOME to C:Program FilesJavajdk1.6.0_21 2 Linux export JAVA_HOME = /usr/local/java-current 3 Mac export JAVA_HOME = /Library/Java/Home Append Java compiler location to System Path. Sr.No. OS & Output 1 Windows Append the string ;%JAVA_HOME%bin to the end of the system variable, Path. 2 Linux export PATH=$PATH:$JAVA_HOME/bin/ 3 Mac not required Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, compile and run a simple program to confirm that the IDE knows where you installed Java, otherwise do proper setup as given document of the IDE. Step 3 – Setup Eclipse IDE All the examples in this tutorial have been written using Eclipse IDE. So I would suggest you should have latest version of Eclipse installed on your machine based on your operating system. To install Eclipse IDE, download the latest Eclipse binaries from https://www.eclipse.org. 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 by executing the following commands on windows machine, or you can simply double click on eclipse.exe %C:eclipseeclipse.exe Eclipse can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine − $/usr/local/eclipse/eclipse After a successful startup, if everything is fine then it should display following result − 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 installed on your machine. After a successful setup for the GWT plugin, if everything is fine then it should display following screen with Google icon marked with red rectangle as shown below − Step 5: Setup Apache Tomcat You can download the latest version of Tomcat from https://tomcat.apache.org/. Once you downloaded the installation, unpack the binary distribution into a convenient location. For example in C:apache-tomcat-6.0.33 on windows, or /usr/local/apache-tomcat-6.0.33 on Linux/Unix and set CATALINA_HOME environment variable pointing to the installation locations. Tomcat can be started by executing the following commands on windows machine, or you can simply double click on startup.bat %CATALINA_HOME%binstartup.bat or /usr/local/apache-tomcat-6.0.33/bin/startup.sh After a successful startup, the default web applications included with Tomcat will be available by visiting http://localhost:8080/. If everything is fine then it should display following result − Further information about configuring and running Tomcat can be found in the documentation included here, as well as on the Tomcat web site − https://tomcat.apache.org/ Tomcat can be stopped by executing the following commands on windows machine − %CATALINA_HOME%binshutdown or C:apache-tomcat-5.5.29binshutdown Tomcat can be stopped by executing the following commands on Unix (Solaris, Linux, etc.) machine − $CATALINA_HOME/bin/shutdown.sh or /usr/local/apache-tomcat-5.5.29/bin/shutdown.sh Print Page Previous Next Advertisements ”;

GWT – Custom Widgets

GWT – Custom Widgets ”; Previous Next GWT provides three ways to create custom user interface elements. There are three general strategies to follow − Create a widget by extending Composite Class − This is the most common and easiest way to create custom widgets. Here you can use existing widgets to create composite view with custom properties. Create a widget using GWT DOM API in JAVA − GWT basic widgets are created in this way. Still its a very complicated way to create custom widget and should be used cautiously. Use JavaScript and wrap it in a widget using JSNI − This should generally only be done as a last resort. Considering the cross-browser implications of the native methods, it becomes very complicated and also becomes more difficult to debug. Create Custom Widget with Composite Class This example will take you through simple steps to show creation of a Custom Widget in GWT. Follow the following steps to update the GWT application we created in GWT – Basic Widgets chapter − Here we are going to create a custom widget by extending Composite class, which is the easiest way to build custom widgets. Step Description 1 Create a project with a name HelloWorld under a package com.tutorialspoint as explained in the GWT – Create Application chapter. 2 Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorld.html and HelloWorld.java as explained below. Keep rest of the files unchanged. 3 Compile and run the 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. –> <inherits name = ”com.google.gwt.user.User”/> <!– Inherit the default GWT style sheet. –> <inherits name = ”com.google.gwt.user.theme.clean.Clean”/> <!– Specify the app entry point class. –> <entry-point class = ”com.tutorialspoint.client.HelloWorld”/> <!– Specify the paths for translatable code –> <source path = ”client”/> <source path = ”shared”/> </module> Following is the content of the modified Style Sheet file war/HelloWorld.css. body { text-align: center; font-family: verdana, sans-serif; } h1 { font-size: 2em; font-weight: bold; color: #777777; margin: 40px 0px 70px; text-align: center; } Following is the content of the modified HTML host file war/HelloWorld.html. <html> <head> <title>Hello World</title> <link rel = “stylesheet” href = “HelloWorld.css”/> <script language = “javascript” src = “helloworld/helloworld.nocache.js”> </script> </head> <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.client; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.ui.CheckBox; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.TextBox; public class HelloWorld implements EntryPoint { /** * A composite of a TextBox and a CheckBox that optionally enables it. */ private static class OptionalTextBox extends Composite implements ClickHandler { private TextBox textBox = new TextBox(); private CheckBox checkBox = new CheckBox(); private boolean enabled = true; public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } /** * Style this widget using .optionalTextWidget CSS class.<br/> * Style textbox using .optionalTextBox CSS class.<br/> * Style checkbox using .optionalCheckBox CSS class.<br/> * Constructs an OptionalTextBox with the given caption * on the check. * @param caption the caption to be displayed with the check box */ public OptionalTextBox(String caption) { // place the check above the text box using a vertical panel. HorizontalPanel panel = new HorizontalPanel(); // panel.setBorderWidth(1); panel.setSpacing(10); panel.add(checkBox); panel.add(textBox); // all composites must call initWidget() in their constructors. initWidget(panel); //set style name for entire widget setStyleName(“optionalTextWidget”); //set style name for text box textBox.setStyleName(“optionalTextBox”); //set style name for check box checkBox.setStyleName(“optionalCheckBox”); textBox.setWidth(“200″); // Set the check box”s caption, and check it by default. checkBox.setText(caption); checkBox.setValue(enabled); checkBox.addClickHandler(this); enableTextBox(enabled,checkBox.getValue()); } public void onClick(ClickEvent event) { if (event.getSource() == checkBox) { // When the check box is clicked, //update the text box”s enabled state. enableTextBox(enabled,checkBox.getValue()); } } private void enableTextBox(boolean enable,boolean isChecked){ enable = (enable && isChecked) || (!enable && !isChecked); textBox.setStyleDependentName(“disabled”, !enable); textBox.setEnabled(enable); } } public void onModuleLoad() { // Create an optional text box and add it to the root panel. OptionalTextBox otb = new OptionalTextBox( “Want to explain the solution?”); otb.setEnabled(true); RootPanel.get().add(otb); } } Once you are ready with all the changes done, let us compile and run the application in development mode as we did in GWT – Create Application chapter. If everything is fine with your application, this will produce following result − You can notice following points Creation of Custom Widget by extending Composite widget is pretty easy. We”ve created a widget with GWT inbuilt widgets, TextBox and CheckBox thus using the concept of reusability. TextBox get disabled/enabled depending on state of checkbox. We”ve provided an API to enable/disable the control. We”ve exposed internal widgets styles via documented CSS styles. Print Page Previous Next Advertisements ”;