The Google Web Toolkit (GWT): Declarative Layout with UiBinder Basics



Similar documents
The Google Web Toolkit (GWT): The Model-View-Presenter (MVP) Architecture Official MVP Framework

Java with Eclipse: Setup & Getting Started

Hadoop Streaming coreservlets.com and Dima May coreservlets.com and Dima May

Hadoop Distributed File System (HDFS) Overview

Virtual Machine (VM) For Hadoop Training

Android Programming: Installation, Setup, and Getting Started

The Google Web Toolkit (GWT): Overview & Getting Started

Android Programming Basics

Map Reduce Workflows

Official Android Coding Style Conventions

Apache Pig Joining Data-Sets

Advanced Java Client API

Building Web Services with Apache Axis2

HBase Java Administrative API

HBase Key Design coreservlets.com and Dima May coreservlets.com and Dima May

2011 Marty Hall An Overview of Servlet & JSP Technology Customized Java EE Training:

Managed Beans II Advanced Features

Android Programming: 2D Drawing Part 1: Using ondraw

HDFS Installation and Shell

Web Applications. Originals of Slides and Source Code for Examples:

Application Security

For live Java EE training, please see training courses

Google Web Toolkit. Progetto di Applicazioni Software a.a. 2011/12. Massimo Mecella

What servlets and JSP are all about

WA 2. GWT Martin Klíma

Debugging Ajax Pages: Firebug

MASTERTAG DEVELOPER GUIDE

JHU/EP Server Originals of Slides and Source Code for Examples:

Web Applications. For live Java training, please see training courses at

HDFS - Java API coreservlets.com and Dima May coreservlets.com and Dima May

Tutorial: Building a Dojo Application using IBM Rational Application Developer Loan Payment Calculator

Client-side Web Engineering From HTML to AJAX

Session Tracking Customized Java EE Training:

Example. Represent this as XML

& JSP Technology Originals of Slides and Source Code for Examples:

Credits: Some of the slides are based on material adapted from

An Overview of Servlet & JSP Technology

Introducing Apache Pivot. Greg Brown, Todd Volkert 6/10/2010

Getting Started: Creating a Simple App

Online Multimedia Winter semester 2015/16

CrownPeak Java Web Hosting. Version 0.20

Google Web Toolkit. Introduction to GWT Development. Ilkka Rinne & Sampo Savolainen / Spatineo Oy

The Google Web Toolkit (GWT): JavaScript Native Interface (JSNI)

MapReduce on YARN Job Execution

Handling the Client Request: Form Data

Hadoop Introduction coreservlets.com and Dima May coreservlets.com and Dima May

Interspire Website Publisher Developer Documentation. Template Customization Guide

Enterprise Application Development In Java with AJAX and ORM

SSC - Web development Model-View-Controller for Java web application development

PLAYER DEVELOPER GUIDE

QML and JavaScript for Native App Development

HTML Form Widgets. Review: HTML Forms. Review: CGI Programs

Basic Java Syntax. Slides 2016 Marty Hall,

Localization and Resources

Novell Identity Manager

Building and Using Web Services With JDeveloper 11g

GUI and Web Programming

Using an external style sheet with Dreamweaver (CS6)

Android Environment SDK

Object-Oriented Programming in Java: More Capabilities

How to Create an Android Application using Eclipse on Windows 7

Advantage of Jquery: T his file is downloaded from

Making Web Application using Tizen Web UI Framework. Koeun Choi

JavaScript Basics & HTML DOM. Sang Shin Java Technology Architect Sun Microsystems, Inc. sang.shin@sun.com

Mobile Web Applications. Gary Dubuque IT Research Architect Department of Revenue

An introduction to creating JSF applications in Rational Application Developer Version 8.0

Interactive Data Visualization for the Web Scott Murray

Rich User Interfaces for Web-Based Corporate Applications

Building A Very Simple Web Site

Software Development Interactief Centrum voor gerichte Training en Studie Edisonweg 14c, 1821 BN Alkmaar T:

Component Based Web Development with Apache Wicket

Android Environment SDK

Importance of the Java Inet Address and Public String Hosting System

NASSI-SCHNEIDERMAN DIAGRAM IN HTML BASED ON AML

Google App Engine f r o r J av a a v a (G ( AE A / E J / )

WIRIS quizzes web services Getting started with PHP and Java

The goal with this tutorial is to show how to implement and use the Selenium testing framework.

Preface. Motivation for this Book

CMSC434 TUTORIAL #3 HTML CSS JavaScript Jquery Ajax + Google AppEngine Mobile WebApp HTML5

Cisco Adaptive Security Appliance (ASA) Web VPN Portal Customization: Solution Brief

Hello World RESTful web service tutorial

Fast track to HTML & CSS 101 (Web Design)

Visualizing an OrientDB Graph Database with KeyLines

Overview. In the beginning. Issues with Client Side Scripting What is JavaScript? Syntax and the Document Object Model Moving forward with JavaScript

Web Development CSE2WD Final Examination June (a) Which organisation is primarily responsible for HTML, CSS and DOM standards?

How To Write An Ria Application

Introduction to Android Development. Jeff Avery CS349, Mar 2013

Creating a 2D Game Engine for Android OS. Introduction

CSC309 Winter 2016 Lecture 3. Larry Zhang

JavaScript By: A. Mousavi & P. Broomhead SERG, School of Engineering Design, Brunel University, UK

Java Server Pages and Java Beans

The Oracle Fusion Development Platform

Implementing Specialized Data Capture Applications with InVision Development Tools (Part 2)

Single Page Web App Generator (SPWAG)

Developing NFC Applications on the Android Platform. The Definitive Resource

Web Design Basics. Cindy Royal, Ph.D. Associate Professor Texas State University

English. Asema.com Portlets Programmers' Manual

Visualizing a Neo4j Graph Database with KeyLines

Modern Web Apps with HTML5 Web Components, Polymer, and Java EE MVC 1.0. Kito Mann Virtua, Inc.

Mobile Web Design with HTML5, CSS3, JavaScript and JQuery Mobile Training BSP-2256 Length: 5 days Price: $ 2,895.00

Transcription:

2013 Marty Hall & Yaakov Chaikin The Google Web Toolkit (GWT): Declarative Layout with UiBinder Basics (GWT 2.5 Version) Originals of Slides and Source Code for Examples: http://courses.coreservlets.com/course-materials/gwt.html Customized Java EE Training: http://courses.coreservlets.com/ GWT, Java 7 and 8, JSF 2, PrimeFaces, HTML5, Servlets, JSP, Ajax, jquery, Spring, Hibernate, REST, Hadoop, Android. Developed and taught by well-known author and developer. At public venues or onsite at your location. 2013 Marty Hall & Yaakov Chaikin For live Ajax & GWT training, see training courses at http://courses.coreservlets.com/. Taught by the author of Core Servlets and JSP, More Servlets and JSP, and this tutorial. Available at public venues, or customized versions can be held on-site at your organization. Courses developed and taught by Marty Hall JSF 2, PrimeFaces, servlets/jsp, Ajax, jquery, Android development, Java 7 or 8 programming, custom mix of topics Courses Customized available in any state Java or country. EE Training: Maryland/DC http://courses.coreservlets.com/ area companies can also choose afternoon/evening courses. GWT, Courses Java 7 developed and 8, JSF and 2, PrimeFaces, taught by coreservlets.com HTML5, Servlets, JSP, experts Ajax, (edited jquery, by Spring, Marty) Hibernate, REST, Hadoop, Android. Spring, Hibernate/JPA, GWT, Hadoop, HTML5, RESTful Web Services Developed and taught by well-known Contact author hall@coreservlets.com and developer. At public for details venues or onsite at your location.

Topics in This Section Problems with only Java-based layout Main idea behind UiBinder approach Advantages of UiBinder Disadvantages of UiBinder Steps for HTML-based UiBinder GUIs Steps for Widget-based UiBinder GUIs Simplified UI event handling with UiBinder 4 2013 Marty Hall & Yaakov Chaikin Overview Customized Java EE Training: http://courses.coreservlets.com/ GWT, Java 7 and 8, JSF 2, PrimeFaces, HTML5, Servlets, JSP, Ajax, jquery, Spring, Hibernate, REST, Hadoop, Android. Developed and taught by well-known author and developer. At public venues or onsite at your location.

Layout Strategies HTML-based layout Write HTML by hand, designate places for individual controls HTML body contains a lot of content Best when GWT is used for A traditional Web app with some pieces of Ajax-enabled content Complex page where HTML layout does not change You need the HTML content indexed by a search engine Java-based layout Attaches main layout panel to HTML <body> element Java uses Panels to build up overall layout Similar to way LayoutManagers are used in desktop Java Best when GWT is used to Mimic a desktop application Create an application where HTML layout changes on fly Declarative layout with UiBinder (this tutorial) 6 HTML-Based Layout 7 HTML <body> Regular HTML <div id="id-1"></div> Regular HTML <div id="id-2"></div> Regular HTML <div id="id-3"></div> Regular HTML </body> Java public void onmoduleload() { SomeWidget w1 = ; RootPanel.get("id-1").add(w1); SomeWidget w2 = ; RootPanel.get("id-2").add(w2); SomeWidget w3 = ; RootPanel.get("id-3").add(w3);

Java-Based Layout HTML <body> <!-- Possibly history iframe, but few or no HTML elements --> </body> Java public void onmoduleload() { SomePanel mainpanel = ; mainpanel.setvariousproperties(); SomeOtherPanel subpanel = ; SomeWidget w1 = ; subpanel.add(w1); mainpanel.add(subpanel); RootLayoutPanel.get().add(mainPanel); 8 9 Problems with Only Java-Based Layout Hard to format HTML in Java Think servlets vs. JSP HTML-based layout is usually not dynamic enough If it is, use it! Hard to visualize the layout Not easy to see final result from looking at Java code Hard to effectively involve a graphic UI Web designer They usually don t know Java Even if you manage to get the design into Java, it is hard to maintain

UiBinder: Main Idea Use XML file to lay out chunk of content Can represent HTML or a Widget Make Java class that represents that chunk of content There are some overly-details steps involved, but Eclipse has shortcuts that automate making most of them Use that Java class in your main application If class represents HTML, use the GWT DOM API to insert it If class represents a Widget, use normal add method to insert it 10 Advantages of UiBinder 11 Can make complex page layouts using HTML Or HTML-like XML Analogous to adding JSP to pure-servlet apps More maintainable Graphic Web designers can be involved from initial design through maintenance Easy to start with regular HTML and gradually sprinkle in GWT bindings Separation of concerns Aesthetics and functionality of UI no longer mashed together Compile-time check of cross references between XML & Java and even within XML itself

Advantages of UiBinder (Continued) Better browser performance Browsers are very fast at stuffing long strings into innerhtml of an element Not so much when it comes to executing JavaScript APIs Lesson: use regular HTML whenever possible! Goal of UiBinder: Make the easier choice the right choice Tooling support Eclipse, NetBeans 12 Disadvantages of UiBinder Causes proliferation of files There are two files for every component Unlike JSP, UiBinder is only declarative No rendering mechanism: no loops, conditionals, etc. It s just a declaration of your layout Still need Java to loop through data and generate output Complex page layouts are done with HTML Wait! What? Didn t I say that was an advantage? Depends on your background and why you chose GWT in the first place 13

2013 Marty Hall & Yaakov Chaikin HTML-Based UiBinder GUIs 14 Customized Java EE Training: http://courses.coreservlets.com/ GWT, Java 7 and 8, JSF 2, PrimeFaces, HTML5, Servlets, JSP, Ajax, jquery, Spring, Hibernate, REST, Hadoop, Android. Developed and taught by well-known author and developer. At public venues or onsite at your location. Basic Steps 15 1. Create XML file Top-level element is an HTML tag like <div> Put raw HTML inside Use ui:field to mark places for later insertion 2. Create Java class that represents the XML Extend UiObject Use UiBinder interface and GWT.create to bind the Java class to the XML representation Mark fields with @UiField (one for each ui:field in XML) Call setelement Insert content into those fields 3. Use new Java class in EntryPoint class Use DOM API with getelement and appendchild Note Eclipse wizard will automate much of this process

Example: HelloHtmlWorld UiBinder Start with Eclipse wizard Created coreservlets.client.ui package (for convenience of organization) Right-clicked on the ui package and chose New Other GWT UiBinder Chose Create UI based on HTML, clicked Finish After creation, removed some generated content we ll learn later about Creates 2 files: HelloHtmlWorld.java and HelloHtmlWorld.ui.xml 16 Step 1: XML File HelloHtmlWorld.ui.xml <!DOCTYPE ui:uibinder SYSTEM "http://dl.google.com/gwt/dtd/xhtml.ent"> <ui:uibinder xmlns:ui="urn:ui:com.google.gwt.uibinder"> <div> Hello, <span ui:field="greetspan"></span> </div> </ui:uibinder> This is considered the root element of the UiBinder declaration, even though the root element of the XML file is ui:uibinder. This is what the Java counterpart needs to treat this declaration as, i.e., div element This is a bound field. There must be a corresponding member of the same name in HelloHtmlWorld.java. It must have at least package private scope, i.e., cannot be private. The type of the corresponding field must be a GWT DOM class that is equivalent to owning tag, i.e., <span>. (SpanElement or its superclass) Regular XML does not define named HTML character entities like and. GWT provides them through the DOCTYPE above. This is already baked into the GWT compiler, so don t need to have Internet access for this to work. 17 Yes, this is DTD and XML Schema declaration in the same file! This is completely legal!

Step 2A: Extend UiObject HelloHtmlWorld.java import com.google.gwt.core.client.gwt; import com.google.gwt.dom.client.*; import com.google.gwt.uibinder.client.*; import com.google.gwt.user.client.ui.uiobject; Only if your root UiBinder element is HTML, i.e., it s an HTML-based UiBinder. In this case, the root UiBinder element is div. In next section, we will use Widget-based UiBinders, so will extend Composite instead. public class HelloHtmlWorld extends UIObject { interface HelloHtmlWorldUiBinder extends UiBinder<DivElement, HelloHtmlWorld> { private static HelloHtmlWorldUiBinder uibinder = GWT.create(HelloHtmlWorldUiBinder.class); @UiField SpanElement greetspan; 18 public HelloHtmlWorld(String greeting) { setelement(uibinder.createandbindui(this)); greetspan.setinnertext(greeting); Step 2B: Use UiBinder & GWT.create to Bind Java to XML Declare marker interface that will tell GWT which two types to attempt binding. Must be GWT type equivalent to the type of root UiBinder element. (DivElement or Element type will work here). import com.google.gwt.user.client.ui.uiobject; Owner type whose @UiFields need to be bound, i.e., type of this class. public class HelloHtmlWorld extends UIObject { interface HelloHtmlWorldUiBinder extends UiBinder<DivElement, HelloHtmlWorld> { private static HelloHtmlWorldUiBinder uibinder = GWT.create(HelloHtmlWorldUiBinder.class); @UiField SpanElement greetspan; 19 public HelloHtmlWorld(String greeting) { setelement(uibinder.createandbindui(this)); greetspan.setinnertext(greeting); GWT creates an instance of a factory that can generate the UI and glue it to the owning class, i.e., this class, associating all the fields with @UiField with its declared counterpart.

Steps 2C 2E public class HelloHtmlWorld extends UIObject { interface HelloHtmlWorldUiBinder extends UiBinder<DivElement, HelloHtmlWorld> { private static HelloHtmlWorldUiBinder uibinder = GWT.create(HelloHtmlWorldUiBinder.class); Step 2C: Mark fields with @UiField (on for each ui:field in the XML). Var name must match ui:field name in ui.xml file. @UiField SpanElement greetspan; public HelloHtmlWorld(String greeting) { setelement(uibinder.createandbindui(this)); greetspan.setinnertext(greeting); Creates the root UiBinder type defined in the interface, i.e., DivElement, passing it an instance of an owner class, i.e., HelloHtmlWorld. 20 Step 2D: call setelement. Before anything can be done with a UIObject instance, setelement method must be called. Tells GWT what HTML element to treat this object as. Step 2E: insert content. Since this represents an HTML Element (SpanElement in this case), not a Widget, we use the lower-level Element methods like setinnertext. Final Result: HelloHtmlWorld.java import com.google.gwt.core.client.gwt; import com.google.gwt.dom.client.*; import com.google.gwt.uibinder.client.*; import com.google.gwt.user.client.ui.uiobject; public class HelloHtmlWorld extends UIObject { interface HelloHtmlWorldUiBinder extends UiBinder<DivElement, HelloHtmlWorld> { private static HelloHtmlWorldUiBinder uibinder = GWT.create(HelloHtmlWorldUiBinder.class); @UiField SpanElement greetspan; 21 public HelloHtmlWorld(String greeting) { setelement(uibinder.createandbindui(this)); greetspan.setinnertext(greeting);

Step 3: Use New Java Class in EntryPoint Class public class GwtUiBinder1 implements EntryPoint { public void onmoduleload() { HelloHtmlWorld hellohtmlworld = new HelloHtmlWorld("UiBinder HTML World!"); Element attachto = RootPanel.get("uibinder-html").getElement(); attachto.appendchild(hellohtmlworld.getelement()); Since the HelloHtmlWorld is a UIObject and not a Widget, we need to use the lower-level DOM API to append it to the browser DOM. 22 Example: Result <fieldset> <legend>simple UiBinder HTML Example</legend> <div id="uibinder-html"></div> </fieldset> <br/> 23

2013 Marty Hall & Yaakov Chaikin Widget-Based UiBinder GUIs 24 Customized Java EE Training: http://courses.coreservlets.com/ GWT, Java 7 and 8, JSF 2, PrimeFaces, HTML5, Servlets, JSP, Ajax, jquery, Spring, Hibernate, REST, Hadoop, Android. Developed and taught by well-known author and developer. At public venues or onsite at your location. Basic Steps (Main Changes from HTML-Based in Red) 25 1. Create XML file Top-level element represents a Widget: <g:somegwtwidget> Put mixture of raw HTML and <g:othergwtwidgets> inside Use ui:field to mark places for later insertion 2. Create Java class that represents the XML Extend Composite Use UiBinder interface and GWT.create to bind the Java class to the XML representation Mark fields with @UiField (one for each ui:field in XML) Call initwidget Set properties of those fields 3. Use new Java class in EntryPoint class Use normal Widget methods (e.g., RootPanel.get( ).add(yourwidget)) Note Eclipse wizard will automate much of this process

Example: HelloWidgetWorld UiBinder Start with Eclipse wizard Created coreservlets.client.ui package (for convenience of organization) Right-clicked on the ui package and chose New-UiBinder Chose Create UI based on GWT widgets, clicked Finish After creation, removed some generated content we ll learn later about Creates 2 files: HelloWidgetWorld.java and HelloWidgetWorld.ui.xml 26 Step 1: XML File <!DOCTYPE ui:uibinder SYSTEM "http://dl.google.com/gwt/dtd/xhtml.ent"> <ui:uibinder xmlns:ui="urn:ui:com.google.gwt.uibinder" xmlns:g="urn:import:com.google.gwt.user.client.ui"> <g:htmlpanel> <span style="font-style: italic;">hello,</span> <g:html ui:field="label" /> </g:htmlpanel> </ui:uibinder> Imports everything in the com.google.gwt.user.client.ui package and gives it an XML namespace prefix g. Now, any class in that package can be referenced here with the prefix g. This is considered the root widget of this UiBinder declaration, even though the root element of the XML file is ui:uibinder. This is what the Java counterpart needs to treat this declaration as, i.e., HTMLPanel This is a bound field. There must be a corresponding member of the same name in HelloWidgetWorld.java. It must have at least package private scope, i.e., can not be private. The type of the corresponding field must be a GWT widget type that is either HTML or its superclass. 27

Step 2A: Extend Composite HelloWidgetWorld.java import com.google.gwt.core.client.gwt; import com.google.gwt.uibinder.client.*; import com.google.gwt.user.client.ui.*; Only if your root UiBinder element is a GWT Widget, i.e., it s a GWT Widget-based UiBinder. In this case, the root UiBinder widget is HTMLPanel, whose superclass is Widget, but we could have used HTMLPanel here just the same. Yes, this IS a custom widget! public class HelloWidgetWorld extends Composite { interface HelloWidgetWorldUiBinder extends UiBinder<Widget, HelloWidgetWorld> { private static HelloWidgetWorldUiBinder uibinder = GWT.create(HelloWidgetWorldUiBinder.class); @UiField HTML label; public HelloWidgetWorld(String greeting) { initwidget(uibinder.createandbindui(this)); label.settext(greeting); 28 Step 2B: Use UiBinder & GWT.create to Bind Java to XML Declare marker interface that will tell GWT which two types to attempt binding. Must be GWT type equivalent to the type of root UiBinder element. (HTMLPanel or Widget type will work here). Owner type whose @UiFields need to be bound, i.e., type of this class. public class HelloWidgetWorld extends Composite { interface HelloWidgetWorldUiBinder extends UiBinder<Widget, HelloWidgetWorld> { private static HelloWidgetWorldUiBinder uibinder = GWT.create(HelloWidgetWorldUiBinder.class); @UiField HTML label; public HelloWidgetWorld(String greeting) { initwidget(uibinder.createandbindui(this)); label.settext(greeting); GWT creates an instance of a factory that can generate the UI and glue it to the owning class, i.e., this class, associating all the fields with @UiField with its declared counterpart. 29

Steps 2C 2E public class HelloWidgetWorld extends Composite { interface HelloWidgetWorldUiBinder extends UiBinder<Widget, HelloWidgetWorld> { 30 private static HelloWidgetWorldUiBinder uibinder = GWT.create(HelloWidgetWorldUiBinder.class); Step 2C: mark fields with @UiField. Must match ui:field name in ui.xml file. @UiField HTML label; public HelloWidgetWorld(String greeting) { initwidget(uibinder.createandbindui(this)); label.settext(greeting); Step 2D: call initwidget. Before anything can be done with a Composite instance, initwidget method must be called. Tells GWT what GWT Widget to treat this object as. (We showed this before when creating custom widgets). Step 2E: Set properties of fields. This is a normal Widget (of type HTML in this case). Creates the root UiBinder type defined in the interface, i.e., Widget, passing it an instance of an owner class, i.e., HelloWidgetWorld. Final Result: HelloWidgetWorld.java import com.google.gwt.core.client.gwt; import com.google.gwt.uibinder.client.*; import com.google.gwt.user.client.ui.*; public class HelloWidgetWorld extends Composite { interface HelloWidgetWorldUiBinder extends UiBinder<Widget, HelloWidgetWorld> { private static HelloWidgetWorldUiBinder uibinder = GWT.create(HelloWidgetWorldUiBinder.class); @UiField HTML label; public HelloWidgetWorld(String greeting) { initwidget(uibinder.createandbindui(this)); label.settext(greeting); 31

Step 3: Use New Java Class in EntryPoint Class public class GwtUiBinder1 implements EntryPoint { public void onmoduleload() { HelloHtmlWorld hellohtmlworld = new HelloHtmlWorld("UiBinder HTML World!"); Element attachto = RootPanel.get("uibinder-html").getElement(); attachto.appendchild(hellohtmlworld.getelement()); HelloWidgetWorld hellowidgetworld = new HelloWidgetWorld("UiBinder Widget World!"); RootPanel.get("uibinder-widget").add(helloWidgetWorld); Since the HelloWidgetWorld is a regular GWT widget, we can directly add it to RootPanel without resorting to GWT DOM API. 32 Example: Result <fieldset> <legend>simple UiBinder Widget Example</legend> <div id="uibinder-widget"></div> </fieldset> <br/> 33

2013 Marty Hall & Yaakov Chaikin Simplified UI Event Handling Customized Java EE Training: http://courses.coreservlets.com/ GWT, Java 7 and 8, JSF 2, PrimeFaces, HTML5, Servlets, JSP, Ajax, jquery, Spring, Hibernate, REST, Hadoop, Android. Developed and taught by well-known author and developer. At public venues or onsite at your location. Summary 35 UI event handling has a lot of boilerplate code Create a class that implements SomeHandler interface Can be done as an anonymous, inner, or standalone Implement the onblah method in that interface Call addsomehandler to the widget In UiBinder, use shortcut: @UiHandler("fieldName") void method(blahevent e) { "fieldname" name of declared member field in this class BlahEvent is any event type, e.g., ClickEvent, BlurEvent, etc. Method name can be anything you want (but can t be private) Disadvantages GWT-created handlers are not sharable with other components You can still refactor and share the functionality Can only be used on widgets, not DOM elements

Random Number and Linked ListBox Example Review <fieldset> <legend>client-side Data</legend> <table border="1"> <tr><th>user Control</th> <th>result</th></tr> <tr><td id="randomnumberbutton"></td> <td id="randomnumberresult"></td></tr> <tr><td>state: <span id="statelistholder"></span></td> <td>city: <span id="citylistholder"></span></td> </tr> </table><br/> </fieldset> 36 Random Number and Linked ListBox Example Review (Cont.) public class GwtApp1 implements EntryPoint { public void onmoduleload() { // Main entry point buttonsetup(); listsetup(); private void buttonsetup() { Button randomnumberbutton = new Button("Show Random Number"); HTML randomnumberresult = new HTML("<i>Num will go here</i>"); randomnumberbutton.addclickhandler (new RanNumHandler(randomNumberResult)); RootPanel.get("randomNumberButton").add(randomNumberButton); RootPanel.get("randomNumberResult").add(randomNumberResult); 37

Random Number and Linked ListBox Example Review (Cont.) private class RanNumHandler implements ClickHandler { private HTML resultregion; public RanNumHandler(HTML resultregion) { this.resultregion = resultregion; public void onclick(clickevent event) { resultregion.settext("number: " + Math.random()*10); 38 Random Number and Linked ListBox Example Review (cont) private void listsetup() { ListBox statelist = new ListBox(); populatestatelist(statelist); statelist.setvisibleitemcount(1); ListBox citylist = new ListBox(); citylist.additem("select City"); citylist.setvisibleitemcount(1); citylist.setenabled(false); statelist.addchangehandler(new StateHandler(stateList, citylist)); RootPanel.get("stateListHolder").add(stateList); RootPanel.get("cityListHolder").add(cityList); 39 private void populatestatelist(listbox statelist) { statelist.additem("select State"); StateInfo[] nearbystates = StateInfo.getNearbyStates(); for(stateinfo state: nearbystates) { statelist.additem(state.getstatename());

Random Number and Linked ListBox Example Review (cont) private class StateHandler implements ChangeHandler { private ListBox statelist, citylist; public StateHandler(ListBox statelist, ListBox citylist) { this.statelist = statelist; this.citylist = citylist; 40 public void onchange(changeevent event) { int index = statelist.getselectedindex(); String state = statelist.getitemtext(index); StateInfo[] nearbystates = StateInfo.getNearbyStates(); String[] cities = StateInfo.findCities(nearbyStates, state); citylist.clear(); for(string city: cities) { citylist.additem(city); citylist.setenabled(true); Random Number and Linked ListBox Example Review: Result 41

Example: UI Event Handling Without UiBinder shortcut: HandleEvents1.ui.xml <!DOCTYPE ui:uibinder SYSTEM "http://dl.google.com/gwt/dtd/xhtml.ent"> <ui:uibinder xmlns:ui="urn:ui:com.google.gwt.uibinder" xmlns:g="urn:import:com.google.gwt.user.client.ui"> <g:htmlpanel> <table border="1"> <tr><th>user Control</th><th>Result</th></tr> <tr> <td><g:button ui:field="numberbutton">show Random Number </g:button></td> <td><g:html ui:field="numberresult">num will go here </g:html></td></tr> <tr><td>state: <g:listbox ui:field="statelist"/></td> <td>city: <g:listbox ui:field="citylist"/></td></tr> </table><br/> </g:htmlpanel> </ui:uibinder> 42 Example: UI Event Handling Without UiBinder shortcut: HandleEvents1.java public class HandleEvents1 extends Composite { private static HandleEvents1UiBinder uibinder = GWT.create(HandleEvents1UiBinder.class); interface HandleEvents1UiBinder extends UiBinder<Widget, HandleEvents1> { @UiField Button numberbutton; @UiField HTML numberresult; @UiField ListBox statelist; @UiField ListBox citylist; 43 public HandleEvents1() { initwidget(uibinder.createandbindui(this)); numberbutton.addclickhandler(new RanNumHandler()); listsetup();

Example: UI Event Handling Without UiBinder shortcut: HandleEvents1.java (continued) private class RanNumHandler implements ClickHandler { public void onclick(clickevent event) { numberresult.settext("number: " + Math.random() * 10); private void listsetup() { populatestatelist(); statelist.setvisibleitemcount(1); citylist.additem("select City"); citylist.setvisibleitemcount(1); citylist.setenabled(false); statelist.addchangehandler(new StateHandler()); 44 private void populatestatelist() { statelist.additem("select State"); StateInfo[] nearbystates = StateInfo.getNearbyStates(); for (StateInfo state : nearbystates) { statelist.additem(state.getstatename()); Example: UI Event Handling Without UiBinder shortcut: HandleEvents1.java (Continued) private class StateHandler implements ChangeHandler { public void onchange(changeevent event) { int index = statelist.getselectedindex(); String state = statelist.getitemtext(index); StateInfo[] nearbystates = StateInfo.getNearbyStates(); String[] cities = StateInfo.findCities(nearbyStates, state); citylist.clear(); for (String city : cities) { citylist.additem(city); citylist.setenabled(true); 45

Example: UI Event Handling Without UiBinder shortcut: GwtUiBinder1.html & EntryPoint Class <fieldset> <legend>ui Event Handling without @UiHandler shortcut</legend> <div id="uibinder-events-without"></div> </fieldset> <p/> public class GwtUiBinder1 implements EntryPoint { public void onmoduleload() { HandleEvents1 events1 = new HandleEvents1(); RootPanel.get("uibinder-events-without").add(events1); 46 Example: UI Event Handling Without UiBinder shortcut: Result 47

Example: UI Event Handling With UiBinder shortcut: HandleEvents2.ui.xml <!DOCTYPE ui:uibinder SYSTEM "http://dl.google.com/gwt/dtd/xhtml.ent"> <ui:uibinder xmlns:ui="urn:ui:com.google.gwt.uibinder" xmlns:g="urn:import:com.google.gwt.user.client.ui"> <g:htmlpanel> <table border="1"> <tr><th>user Control</th><th>Result</th></tr> <tr> <td><g:button ui:field="numberbutton">show Random Number </g:button></td> <td><g:html ui:field="numberresult">num will go here </g:html></td></tr> <tr><td>state: <g:listbox ui:field="statelist"/></td> <td>city: <g:listbox ui:field="citylist"/></td></tr> </table><br/> </g:htmlpanel> </ui:uibinder> No Changes. Same as HandleEvents1.ui.xml. 48 Example: UI Event Handling With UiBinder shortcut: HandleEvents2.java public class HandleEvents2 extends Composite { private static HandleEvents2UiBinder uibinder = GWT.create(HandleEvents2UiBinder.class); interface HandleEvents2UiBinder extends UiBinder<Widget, HandleEvents2> { @UiField Button numberbutton; @UiField HTML numberresult; @UiField ListBox statelist; @UiField ListBox citylist; public HandleEvents2() { initwidget(uibinder.createandbindui(this)); listsetup(); 49

Example: UI Event Handling With UiBinder shortcut: HandleEvents2.java (continued) GWT matches field name with the @UiField Button numberbutton; value of @UiHandler annotation. @UiField HTML numberresult; @UiField ListBox statelist; @UiField ListBox citylist; @UiHandler("numberButton") void displayrandomnumber(clickevent event) { numberresult.settext("number: " + Math.random() * 10); Must be either public or package private (i.e., default) scope. Can t be a private method. In this example, it is void, but any return type is valid. Based on the event type, this handler will respond to an onclick event. 50 Example: UI Event Handling With UiBinder shortcut: HandleEvents2.java (continued) 51 private void listsetup() { populatestatelist(); statelist.setvisibleitemcount(1); citylist.additem("select City"); citylist.setvisibleitemcount(1); citylist.setenabled(false); @UiHandler("stateList") void handlestatechange(changeevent event) { int index = statelist.getselectedindex(); String state = statelist.getitemtext(index); The contents of the method are the same as before, but now no boilerplate code! StateInfo[] nearbystates = StateInfo.getNearbyStates(); String[] cities = StateInfo.findCities(nearbyStates, state); citylist.clear(); for (String city : cities) { citylist.additem(city); citylist.setenabled(true);

Example: UI Event Handling Without UiBinder shortcut: GwtUiBinder1.html & EntryPoint Class <fieldset> <legend>ui Event Handling with @UiHandler shortcut</legend> <div id="uibinder-events-with"></div> </fieldset> <p/> public class GwtUiBinder1 implements EntryPoint { public void onmoduleload() { HandleEvents2 events2 = new HandleEvents2(); RootPanel.get("uibinder-events-with").add(events2); 52 Example: UI Event Handling With UiBinder shortcut: Result 53

2013 Marty Hall & Yaakov Chaikin Wrap-Up Customized Java EE Training: http://courses.coreservlets.com/ GWT, Java 7 and 8, JSF 2, PrimeFaces, HTML5, Servlets, JSP, Ajax, jquery, Spring, Hibernate, REST, Hadoop, Android. Developed and taught by well-known author and developer. At public venues or onsite at your location. Summary: HTML-Based (Eclipse Wizard Builds #1 & #2) 1. Create XML file Top-level element is an HTML tag like <div> Put raw HTML inside Use ui:field to mark places for later insertion 2. Create Java class that represents the XML Extend UiObject Use UiBinder interface and GWT.create to bind the Java class to the XML representation Mark fields with @UiField (one for each ui:field in XML) Call setelement Insert content into those fields 3. Use new Java class in EntryPoint class Use DOM API with getelement and appendchild 55

Summary: Widget-Based (Eclipse Wizard Builds #1 & #2) 56 1. Create XML file Top-level element represents a Widget: <g:somegwtwidget> Put mixture of raw HTML and <g:othergwtwidgets> inside Use ui:field to mark places for later insertion 2. Create Java class that represents the XML Extend Composite Use UiBinder interface and GWT.create to bind the Java class to the XML representation Mark fields with @UiField (one for each ui:field in XML) Call initwidget Set properties of those fields 3. Use new Java class in EntryPoint class Use normal Widget methods E.g., RootPanel.get( ).add(yourwidget) 2013 Marty Hall & Yaakov Chaikin Questions? JSF 2, PrimeFaces, Java 7 or 8, Ajax, jquery, Hadoop, RESTful Web Services, Android, HTML5, Spring, Hibernate, Servlets, JSP, GWT, and other Java EE training. Customized Java EE Training: http://courses.coreservlets.com/ GWT, Java 7 and 8, JSF 2, PrimeFaces, HTML5, Servlets, JSP, Ajax, jquery, Spring, Hibernate, REST, Hadoop, Android. Developed and taught by well-known author and developer. At public venues or onsite at your location.