|
|||||
![]() Web
Design & Development CS506
VU
Lesson
11
Event
Handling
One
of the most important aspects of
most non-trivial applications
(especially UI type- apps) is
the
ability
to respond to events that
are generated by the various components
of the application, both in
response
to user interactions and other
system components such as
client-server processing. In
this
handout
we will look at how Java
supports event generation and
handling and how to create
(and
process)
custom events.
GUIs
generate events when the
user interacts with GUI. For
example,
--
Clicking a button
--
Moving the mouse
--
Closing Window etc
Both
AWT and swing components (not
all) generate events
--
java.awt.event.*;
--
javax.swing.event.*;
In
java, events are represented
by Objects
These
objects tells us about event
and its source. Examples
are:
--
ActionEvent (Clicking a
button)
--
WindowEvent (Doing something
with window e.g. closing ,
minimizing)
Some
event classes of java.awt.event
are shown in diagram
below
Event
Handling Model
In
Java both AWT and Swing
components use Event
Delegation Model.
In
this model processing of an
event is delegated to a particular object
(handlers )
in the
program
It's
a Publish-Subscribe model. That is, event generating component
publish an event and
event
handling components subscribe
for that event. The
publisher sends these events
to
subscribers.
Similar to the way that you
subscribe for newspaper and
you get the newspaper at
90
![]() Web
Design & Development CS506
VU
your
home from the
publisher.
This
model separates UI code from
program logic, it means that
we can create
separate
classes
for UI components
and event handlers
and hence business/program
logic is
separated
from GUI components.
Event
Handling Steps
For a
programmer the event Handling is a three
step process in terms of
code
Step 1:
Create
components which can
generate events (Event
Generators)
Step 2:
Build
component (objects) that can handle
events (Event
Handlers)
Step 3:
Register
handlers with
generators
Event
Handling Process
Step 1:
Event Generators
The
first step is that you
create an event generator. You have
already seen a lot of event
generators
like:
Buttons
Mouse
Key
Window etc
Most
of GUI components can be created by
calling their constructors. For
example
JButton
b1 = new JButton("Hello");
Now
b1 can generate
events
Note:
We do
not create Mouse/Keys etc as
they are system
components
Step 2:
Event Handlers/ Event
Listener
The
second step is that you
build components that can
handle events
First
Technique - By
Implementing Listener
Interfaces
Java
defines interfaces for every
event type
If a
class needs to handle an
event. It needs to implement the
corresponding listener
interface
To
handle "ActionEvent" a class
needs to implement
"ActionListener"
To
handle "KeyEvent" a class
needs to implement
"KeyListener"
To
handle "MouseEvent" a class
needs to implement "MouseListener" and so
on
Package
java.awt.event contains different event
Listener Interfaces which
are shown in the
following
figure
91
![]() Web
Design & Development CS506
VU
Some
Example Listeners, the way
they are defined in JDK by
Sun
public
interface ActionListener
{
public
void actionPerformed(ActionEvent
e);
}
public
interface ItemListener
{
public
void itemStateChanged(ItemEvent e);
}
public
interface ComponentListener
{
public
void componentHidden(ComponentEvent e);
public
void componentMoved(ComponentEvent
e);
public
void componentResized(ComponentEvent
e);
public
void componentShown(ComponentEvent e);
}
By
implementing an interface the class
agrees to implement all the
methods that are present
in
that
interface. Implementing an interface is
like signing
a contract.
Inside
the method the class can do what
ever it wants to do with
that event
Event
Generator and Event Handler
can be the same or different
classes
To
handle events generated by
Button. A class
needs to
implement
ActionListener
interface and thus needs to
provide the definition of
actionPerformed()
method
which is present in this
interface.
public
class Test implements
ActionListener{
92
![]() Web
Design & Development CS506
VU
public
void actionPerformed(ActionEvent ae)
{
// do
something
}
}
Step 3:
Registering Handler with
Generator
The
event generator is told about the
object which can handle
its events
Event
Generators have a method
--
addXXXListener(_reference to the object of
Handler class_)
For
example, if b1 is JButton then
--
b1.addActionListener(this); // if listener and
generator are same
class
Event
Handling Example
Clicking
the "Hello" button will open
up a message dialog shown
below.
We
will take the simplest approach of
creating handler and generator in a
single class. Button is
our
event
generator and to handle that
event our class needs to
implement ActionListener Interface
and
to
override its actionPerformed method and in last to do
the registration
1.
import java.awt.*;
2.
import javax.swing.*;
3.
import java.awt.event.*;
/*
Implementing the interface according to
the type of the event, i.e. creating
event
handler
(first part of step 2 of our
process) */
4.
public class ActionEventTest
implements
ActionListner{
5.
JFrame
frame;
6.
JButton
hello;
// setting
layout components
7.
public
void initGUI ( ) {
8.
frame = new
JFrame();
9.
Container cont =
frame.getContentPane();
10.
cont.setLayout(new
FlowLayout());
//Creating
event generator step-1 of our
process
11.
hello =
new JButton("Hello");
93
![]() Web
Design & Development CS506
VU
/* Registering
event handler with event
generator.
Since
event handler is in same object that
contains
button,
we have used this to pass the
reference.(step
3 of the
process) */
12.
hello.addActionListener(this);
13.
cont.add(hello);
14.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
15.
frame.setSize(150, 150);
16.
frame.setVisible(true);
17.
}
//constructor
18.
public ActionEventTest ( ) {
19.
initGUI();
20.
}
/*
Override actionPerformed method of
ActionListener's
interfacemethod of
which will be called when
event
takes
place (second part of step 2 of
our process) */
21.
public void actionPerformed(ActionEvent
event) {
22.
JOptionPane.showMessageDialog(null,"Hello is
pressed");
23.
}
24.
public static void
main(String args[]) {
25.
ActionEventTest aeTest = new
ActionEventTest();
26.
}
27.}
// end class
How
Event Handling Participants interact
Behind the
Scenes?
We have
already seen that what a
programmer needs to do handle events.
Let's see what takes
place
behind
the scenes, i.e How JVM
handles event. Before doing
that lets revisit different
participants of
Event
Handling Process and briefly
what they do.
1.
Event Generator / Source
Swing
and awt components
For
example, JButton, JTextField, JFrame
etc
Generates
an event object
Registers
listeners with itself
2.
Event Object
Encapsulate
information about event that
occurred and the source of that
event
For
example, if you click a button,
ActionEvent object is
created
3.
Event Listener/handler
Receives
event objects when notified,
then responds
Each
event source can have
multiple listeners registered on it
94
![]() Web
Design & Development CS506
VU
Conversely,
a single listener can register
with multiple event
sources
4.
JVM
Receives
an event whenever one is
generated
Looks
for the listener/handler of that
event
If
exist, delegate it for
processing
If
not, discard it (event).
When
button generates an ActionEvent it is
sent to JVM which puts it in an
event queue. After
that
when
JVM find it appropriate it de-queue the
event object and send it to
all the listeners that
are
registered
with that button. This is
all what we shown in the pictorial
form below:
(figure
from JAVA A Lab
Course)
Making
Small Calculator
User
enters numbers in the provided
fields
On
pressing "+" button, sum
would be displayed in the answer
field
On
pressing "*" button, product
would be displayed in the answer
field
95
![]() Web
Design & Development CS506
VU
Example
Code: Making Small
Calculator
1.
import java.awt.*;
2.
import javax.swing.*;
3.
import java.awt.event.*;
4.
public class SmallCalcApp implements
ActionListener{
5.
JFrame
frame;
6.
JLabel
firstOperand, secondOperand,
answer;
7.
JTextField
op1, op2, ans;
8.
JButton
plus, mul;
9. // setting
layout
10.
public void initGUI ( )
{
11.
frame = new
JFrame();
12.
firstOperand = new
JLabel("First Operand");
13.
secondOperand
= new JLabel("Second Operand");
14.
answer
= new
JLabel("Answer");
15.
op1 =
new JTextField (15);
16.
op2 =
new JTextField (15);
17.
ans =
new JTextField (15);
18.
plus = new
JButton("+");
19.
plus.setPreferredSize(new
Dimension(70,25));
20.
mul =
new JButton("*");
21.
mul.setPreferredSize(new
Dimension(70,25));
22.
Container
cont = frame.getContentPane();
23.
cont.setLayout(new
FlowLayout());
24.
cont.add(firstOperand);
25.
cont.add(op1);
96
![]() Web
Design & Development CS506
VU
26.
cont.add(secondOperand);
27.
cont.add(op2);
28.
cont.add(plus);
29.
cont.add(mul);
30.
cont.add(answer);
31.
cont.add(ans);
32.
plus.addActionListener(this);
33.
mul.addActionListener(this);
34.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
35.
frame.setSize(200,
220);
36.
frame.setVisible(true);
37.
}
38.
//constructor
39.
public
SmallCalcApp ( ) {
40.
initGUI();
41.
}
42.
public void actionPerformed(ActionEvent
event) {
43.
String
oper, result;
44.
int
num1, num2, res;
/* All the
information regarding an event is
contained
inside
the event object. Here we are calling
the
getSource()
method on the event object to figure
out
the
button that has generated
that event. */
45.
if
(event.getSource() == plus) {
46.
oper =
op1.getText();
47.
num1 =
Integer.parseInt(oper);
48.
oper =
op2.getText();
49.
num2 =
Integer.parseInt (oper);
50.
res =
num1+num2;
51.
result
= res+"";
52.
ans.setText(result);
53.
}
54.
else if
(event.getSource() == mul) {
55.
oper =
op1.getText();
56.
num1 =
Integer.parseInt(oper);
57.
oper =
op2.getText();
58.
num2 =
Integer.parseInt (oper);
97
![]() Web
Design & Development CS506
VU
59.
res =
num1*num2;
60.
result
= res+"";
61.
ans.setText(result);
62.
}
63.
public
static void main(String
args[]) {
64.
SmallCalcApp
scApp = new SmallCalcApp();
65.
}
66.
}// end class
98
Table of Contents:
|
|||||