The Google Web Toolkit (GWT) Widget Event Handling

AMInternet and Web Development

Dec 3, 2011 (5 years and 6 months ago)

625 views

© 2010 Marty Hall
The Goo
g
le Web Toolkit
(
GWT
)
:
g ( )
Wid
g
et Event Handlin
g
(
GWT 2.1
V
ersion
)
Originals of Slides and Source Code for Examples:
htt
p
://courses.coreservlets.com/Course-Materials/
g
wt.html
(
)
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
p
g
© 2010 Marty Hall
For live Ajax & GWT training, see training
t htt//l t/
courses

a
t htt
p:
//
courses.coreserv
l
e
t
s.com
/
.
Taught by the author of Core Servlets and JSP,
More
Servlets and JSP
and this tutorial Available at
More
Servlets and JSP
,
and this tutorial
.
Available at
public venues, or customized versions can be held
on-site at your
organization.
C d l d d t ht b M t H ll
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.

C
ourses
d
eve
l
ope
d
an
d

t
aug
ht

b
y
M
ar
t
y
H
a
ll
– Java 6, servlets/JSP (intermediate and advanced), Struts, JSF 1.x, JSF 2.0, Ajax, GWT 2.0 (with GXT), custom mix of topics
– Ajax courses can concentrate on 1 library (jQuery, Prototype/Scriptaculous, Ext-JS, Dojo, Google Closure) or survey several
• Courses developed and taught by coreservlets.com experts (edited by Marty)
– Spring, Hibernate/JPA, EJB3, Web Services, Ruby/Rails
Contact hall@coreservlets.com for details
Topics in This Section
• Main approaches to event handling
– Separate event handler classes
– Main class implementing event handler interface
Named inner classes

Named

inner

classes
– Anonymous inner classes

Basic widgets and their associated events
Basic

widgets

and

their

associated

events
– Pushbuttons and related widgets
– Checkboxes and related widgets
– Listboxes and related widgets
– Textfields and related widgets
5
© 2010 Marty Hall
Idea
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
General Approach
• Make a control
T B
fi ld
T B
()

T
ext
B
ox text
fi
e
ld
= new
T
ext
B
ox
()
;
• Attach an event handler (4 alternative ways)

textfield.addKe
y
U
p
Handle
r
(
new M
y
Ke
y
U
p
Handle
r
());
y p
(
y y p
());
• MyKeyUpHandler is class that implements KeyUpHandler
– textfield.addKeyUpHandler(this);
• Current class
(
this
)
im
p
lements Ke
y
U
p
Handle
r
( ) p y p
– textfield.addKeyUpHandler (new MyKeyUpHandler());
• MyKeyUpHandler is inner class that implements KeyUpHandler

textfield.addKeyUpHandler
(newKeyUpHandler ()
{...});
textfield.addKeyUpHandler
(new

KeyUpHandler

()

{

...});
• Note
– This is exactly the same approach as with Swing, AWT, or SWT
Y it t h dl i th t t i i

Y
ou wr
it
e even
t

h
an
dl
ers us
i
ng
th
e same s
t
ra
t
eg
i
es as
i
n
desktop Java GUI programming, even though code gets
compiled to JavaScript and HTML at runtime
7
© 2010 Marty Hall
Option 1:Separate
Option

1:

Separate

Handler Classes
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Idea
• Monitor a textfield
E h f fi ld bl ll

E
c
h
o contents o
f
text
fi
e
ld
to ta
bl
e ce
ll
– If textfield contents match “gwt”, give special message
• A
pp
roach
pp
– Use an external class that implements KeyUpHandler
• Advantages
Separate classes generally promote loose coupling

Separate

classes

generally

promote

loose

coupling
• Event handler can be changed independently from rest of app
– Works even if you have multiple textfields to which you attach
different
handlers
different

handlers
• Disadvantages
– If you want to call code in main class, you need reference
E h d i i l b bli

E
ven t
h
en, co
d
e
i
n ma
i
n c
l
ass must
b
e pu
bli
c
9
Main Class
public class GwtEvents1 implements EntryPoint {
p
rivate TextBox textfield;
p
public HTML resultArea;
public void onModuleLoad() {
textfield = new
TextBox
();
textfield

=

new

TextBox
();
textfield.addKeyUpHandler(new WowHandler(this));
resultArea = new HTML("<i>Result will go here</i>");
RootPanel.get().addStyleName("tan");
t l t
("
t tfi ld
") dd(
t tfi ld
)
Roo
t
Pane
l
.ge
t
("
t
ex
tfi
e
ld
ID
")
.a
dd(
t
ex
tfi
e
ld
)
;
RootPanel.get("resultID").add(resultArea);
}
public void backgroundRed() {
RootPanel.get().addStyleName("red");
}
public void backgroundNormal() {
RootPanel.get().removeStyleName("red");
}}
10
Handler Class
public class WowHandler implements KeyUpHandler {
p
rivate GwtEvents1 a
pp;
p pp;
public WowHandler(GwtEvents1 app) {
this.app = app;
}
}
public void onKeyUp(KeyUpEvent event) {
TextBox textfield = (TextBox)event.getSource();
String text = textfield.getText();
if(text.equalsIgnoreCase("gwt")) {
app.resultArea.setHTML("<span class='wow'>Wow!</span>");
app
backgroundRed
();
app
.
backgroundRed
();
} else {
app.resultArea.setHTML(text);
app.backgroundNormal();
}
}
}
11
You need to call main application, so you need to store and use a reference to it. Data in main app must be public.
HTML
...
<link
rel
="
stylesheet
"
<link

rel
stylesheet
href="./css/styles.css"
type="text/css"/>
<
scri
p
t t
yp
e="text/
j
avascri
p
t" lan
g
ua
g
e="
j
avascri
p
t"
p yp j p g g j p
src="gwtevents1/gwtevents1.nocache.js"></script>
</head>
<body>
Left in from auto
-
generated code
...
<table border="1">
<tr><th>Input</th>
<
th
>R lt</
th
></
t
>
Left in from auto
-
generated code
<
th
>R
esu
lt</
th
></
t
r
>
<tr><td id="textfieldID"></td>
<td id="resultID"></td></tr>
</table><
br
/>
</table><
br
/>
...
12
ids match values passed to RootPanel.get in main Java class
CSS (Same in All Examples)
.red { background-color: red }
wow { background
-
color:yellow;
.
wow

{

background
-
color:

yellow;
color: red;
font-weight: bold;
font
size:20px;
font
-
size:

20px;
font-family: Arial, Helvetica, sans-serif;
border-style: inset;
}
}
...
13
Results (Development Mode)
14
© 2010 Marty Hall
O
p
tion 2: Main Class
p
Implementing Handler
Interface
Interface
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Idea
• Monitor a textfield
E h t t f t tfi ld t t bl ll

E
c
h
o con
t
en
t
s o
f

t
ex
tfi
e
ld

t
o
t
a
bl
e ce
ll
– If textfield contents match “gwt”, give special message
• Approach

Have main class implement Ke
y
UpHandle
r
• Advantages

No need to
p
ass main class reference to handle
r
p
– Handler can easily access data in the main class
– Methods or variables in main class can be private

Disadvantages
Disadvantages
– Works well for interfaces, but not allowed for abstract classes
• E.g., adapter classes for interfaces that have multiple methods

Extra work if you have multiple textfields to which you attach
Extra

work

if

you

have

multiple

textfields

to

which

you

attach

different behaviors
• You need if/then/else in the event handler to determine which
textfield you are dealing with
16
Main Class
public class GwtEvents2 implements EntryPoint, KeyUpHandler {
p
rivate TextBox textfield;
p
private HTML resultArea;
public void onModuleLoad() {
textfield = new
TextBox
();
textfield

=

new

TextBox
();
textfield.addKeyUpHandler(this);
resultArea = new HTML("<i>Result will go here</i>");
RootPanel.get().addStyleName("tan");
t l t
("
t tfi ld
") dd(t tfi ld)
Roo
t
Pane
l
.ge
t
("
t
ex
tfi
e
ld
ID
")
.a
dd(t
ex
tfi
e
ld)
;
RootPanel.get("resultID").add(resultArea);
}
private void backgroundRed() {
RootPanel.get().addStyleName("red");
}
private void backgroundNormal() {
RootPanel.get().removeStyleName("red");
}
17
Main Class (Continued)
public void onKeyUp(KeyUpEvent event) {
Strin
g
text = textfield.
g
etText
();
g
g
();
if(text.equalsIgnoreCase("gwt")) {
resultArea.setHTML("<span class='wow'>Wow!</span>");
backgroundRed();
} l {
}
e
l
se
{
resultArea.setHTML(text);
backgroundNormal();
}
}
}
}
Can easily call methods in main class (even private ones), since onKeyUp is part of main class.
18
HTML
(Same As Before Except for JavaScript File Name)
(Same

As

Before

Except

for

JavaScript

File

Name)
...
<link
rel
="
stylesheet
"
<link

rel
stylesheet
href="./css/styles.css"
type="text/css"/>
<script type="text/javascript" language="javascript"
src="gwtevents2/gwtevents2.nocache.js"></script
>
</head>
<body>
Left in from auto
-
generated code
...
<table border="1">
<tr><th>Input</th>
<th>Result</th></tr
>
Left in from auto
-
generated code
<tr><td id="textfieldID"></td>
<td id="resultID"></td></tr>
</table><br/>
...
19
ids match values passed to RootPanel.get in main Java class
Results (Development Mode)
20
© 2010 Marty Hall
Option 3:
Option

3:
Named Inner Classes
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Idea
• Monitor a textfield
E h f fi ld bl ll

E
c
h
o contents o
f
text
fi
e
ld
to ta
bl
e ce
ll
– If textfield contents match “gwt”, give special message
• A
pp
roach
pp
– Use inner class that extends KeyUpHandler
• Advantages
Same advantages as interface (access to main class
data)

Same

advantages

as

interface

(access

to

main

class

data)
– Plus, would work for abstract adapter classes
– Scales well if you have multiple textfields with different behaviors
• Disadvantages
– Little advantage (vs. implementing interface) if handler interface
has only one method and you have only one textfield
• Most GWT handlers have only one method
– Slightly more complex than interface approach
22
Main Class
public class GwtEvents3 implements EntryPoint {
p
rivate TextBox textfield;
p
private HTML resultArea;
public void onModuleLoad() {
textfield = new
TextBox
();
textfield

=

new

TextBox
();
textfield.addKeyUpHandler(new WowHandler());
resultArea = new HTML("<i>Result will go here</i>");
RootPanel.get().addStyleName("tan");
t l t
("
t tfi ld
") dd(t tfi ld)
Roo
t
Pane
l
.ge
t
("
t
ex
tfi
e
ld
ID
")
.a
dd(t
ex
tfi
e
ld)
;
RootPanel.get("resultID").add(resultArea);
}
private void backgroundRed() {
RootPanel.get().addStyleName("red");
}
private void backgroundNormal() {
RootPanel.get().removeStyleName("red");
}
23
Main Class (Continued)
private class WowHandler implements KeyUpHandler {
p
ublic void onKe
y
U
p
(
Ke
y
U
p
Event event
)

{
p
y p
(
y p
) {
String text = textfield.getText();
if(text.equalsIgnoreCase("gwt")) {
resultArea.setHTML("<span class='wow'>Wow!</span>");
backgroundRed
();
backgroundRed
();
} else {
resultArea.setHTML(text);
backgroundNormal();
}
}
}
}
}
24
HTML
(Same As Before Except for JavaScript File Name)
(Same

As

Before

Except

for

JavaScript

File

Name)
...
<link
rel
="
stylesheet
"
<link

rel
stylesheet
href="./css/styles.css"
type="text/css"/>
<script language='javascript'
src='coreservlets.GwtEventsApp3.nocache.js'
>
</script>
</head>
<body>
Left in from auto
-
generated code
<body>
...
<table border="1">
<tr><th>Input</th
>
Left in from auto
-
generated code
<th>Result</th></tr>
<tr><td id="textfieldID"></td>
<td id="resultID"></td></tr>
</t bl ><b/>
</t
a
bl
e
><b
r
/>
...
25
ids match values passed to RootPanel.get in main Java class
Results (Development Mode)
26
© 2010 Marty Hall
Option 4:Anonymous
Option

4:

Anonymous

Inner Classes
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Idea
• Monitor a textfield
– Echo contents of textfield to table cell
– If textfield contents match “gwt”, give special message
Approach

Approach
– Use anonymous inner class that extends KeyUpHandler

Advantages

Advantages
–Same advantages as inner classes
–Shorter
• Disadvantages
– More complex than named inner classes
– Small performance penalties in resultant JavaScript
• May disappear in later GWT versions
28
Main Class
public class GwtEvents4 implements EntryPoint {
p
rivate TextBox textfield;
p
private HTML resultArea;
private void backgroundRed() {
RootPanel get
()
addStyleName
(
"
red
"
);
RootPanel
.
get
()
.
addStyleName
( red );
}
private void backgroundNormal() {
t l t
()
St l
("d")
Roo
t
Pane
l
.ge
t
()
.remove
St
y
l
eName
("
re
d")
;
}
29
Main Class (Continued)
public void onModuleLoad() {
textfield = new TextBox
();
();
textfield.addKeyUpHandler(new KeyUpHandler() {
public void onKeyUp(KeyUpEvent event) {
String text = textfield.getText();
if(
text equalsIgnoreCase
("
gwt
")) {
if(
text
.
equalsIgnoreCase
("
gwt
"))

{
resultArea.setHTML("<span class='wow'>Wow!</span>");
backgroundRed();
} else {
resultArea.setHTML(text);
backgroundNormal();
}
}
Inner-class code refers only to instance variables and new local
variables. If you refer to local variables of the outside code, those
variables must be declared final. This is not particular to GWT, but is
a general requirement in Java for anonymous inner classes.
}
});
resultArea = new HTML("<i>Result will go here</i>");
RootPanel.get().addStyleName("tan");
RootPanel.get("textfieldID").add(textfield);
RootPanel.get("resultID").add(resultArea);
}
}
30
HTML
(Same As Before Except for JavaScript File Name)
(Same

As

Before

Except

for

JavaScript

File

Name)
...
<link
rel
="
stylesheet
"
<link

rel
stylesheet
href="./css/styles.css"
type="text/css"/>
<script type="text/javascript" language="javascript"
src="gwtevents4/gwtevents4.nocache.js"></script
>
</head>
<body>
Left in from auto
-
generated code
...
<table border="1">
<tr><th>Input</th>
<th>Result</th></tr
>
Left in from auto
-
generated code
<tr><td id="textfieldID"></td>
<td id="resultID"></td></tr>
</table><br/>
...
31
ids match values passed to RootPanel.get in main Java class
Results (Development Mode)
32
© 2010 Marty Hall
Basic Widgets and
Basic

Widgets

and

Their Handlers
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Compatibility Note
• Early GWT versions
– Used BlahListene
r
(with Widget as argument)
• ClickListener, FocusListener, etc.

Had a single keyboard listener

Had

a

single

keyboard

listener
• KeyboardListener
• Recent GWT versions (GWT 1.5+)
– Use BlahHandler (with BlahEvent as argument)
• ClickHandler, FocusHandler, etc.
Have multiple keyboard listeners

Have

multiple

keyboard

listeners
• KeyUpHandler, KeyDownHandler, KeyPressHandler
• GXT
(
from ext
j
s.com
)
( j )
– Called BlahListener, but more closely follows the GWT
1.5 approach
34
Button and PushButton
• Purpose
– To initiate an action
• Button is normal HTML button

PushButton
is customimage button
PushButton
is

custom

image

button
• Main handler
– ClickHandler
• onClick(ClickEvent event)
• Auxiliary handlers
F H dl

F
ocus
H
an
dl
er
• onFocus(Widget sender)
– Ke
y
DownHandler
,
Ke
y
U
p
Handler
,
Ke
y
PressHandler
y
,y p,
y
• onKeyDown, onKeyUp, onKeyPress (see TextBox)
35
CheckBox, ToggleButton, and
RadioButton
RadioButton
• Purpose
– To choose between two options
• CheckBox, ToggleButton

To choose among several options

To

choose

among

several

options
• RadioButton
• Main handler
– ClickHandler
• onClick(ClickEvent event)
Auxiliary handlers

Auxiliary

handlers
– FocusHandler

o
nF
ocus
(
F
ocus
Ev
e
n
t
e
v
e
n
t)
o ocus
(
ocus e t
e e t)
– KeyDownHandler, KeyUpHandler, KeyPressHandler
• onKeyDown, onKeyUp, onKeyPress (see TextBox)
36
ListBox
• Purpose
– To choose one of options from list
• setMultipleSelect(false)

To choose several of options fromlist

To

choose

several

of

options

from

list
• setMultipleSelect(false)
• Main handler
– ChangeHandler
• onChange(ChangeEvent event)
Auxiliary
handlers

Auxiliary

handlers
– ClickHandler

FocusHandler
FocusHandler
– KeyDownHandler, KeyUpHandler, KeyPressHandler
37
TextBox, PasswordTextBox,
TextArea
SuggestBox
TextArea
,
SuggestBox
• Purpose
– To collect text

Main
handlers

Main

handlers
– KeyDownHandler, KeyUpHandler, KeyPressHandler
• onKe
y
Down
(
Ke
y
DownEvent event
)
y
(
y
)
• onKeyUp(KeyUpEvent event)
• onKeyPress(KeyPressEvent event)

Auxiliary
handlers

Auxiliary

handlers
– ChangeHandler
– ClickHandler
– FocusHandler
38
© 2010 Marty Hall
Wrap-Up
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Summary
• Separate handler classes

Pro:more modular
Pro:

more

modular
– Cons: hard to call code in main app
– Least common approach

Main class implementing
handler interface
Main

class

implementing

handler

interface
– Pro: easy to call code in main app
– Cons: harder if multiple methods in interface or multiple controls
– My favorite approach when interface has one method and I am
h dli l l i h h
h
an
dli
n
g
on
ly
one contro
l
w
i
t
h
t
h
at event t
y
pe
• Named inner classes
– Pro: good if you have multiple textfields with different behaviors
Cons:slightl more comple

Cons:

slightly

more

comple
x
– My favorite when interface has multiple methods or when handling
multiple controls with the same event types. My overall favorite.

Anonymous inner classes
Anonymous

inner

classes
– Pro: short and succinct
– Cons: more complex, small performance penalty
– Favorite approach of many Swing and SWT developers
40
© 2010 Marty Hall
Questions?
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.