Event Handling
Unit III
1
Event Handling
Any program that uses GUI (graphical user
interface) such as Java application written for
windows, is event driven.
Event describes the change of state of any
object.
Events are generated as result of user interaction
with the graphical user interface components.
2
• Changing the state of an object is known as an
event.
• For example: clicking on a button, Entering a
character in Textbox, moving the mouse,
selecting an item from list, scrolling the page,
etc.
• The java.awt.event package provides many
event classes and Listener interfaces for event
handling.
3
Delegation Event Model
• The modern approach to handling events is
based on the delegation event model.
• The delegation event model provides a
standard mechanism for a source to
generate an event and send it to a set of
listeners.
4
Delegation Event Model
• Its concept is quite simple: a source generates an
event and sends it to one or more listeners.
• In this scheme, the listener simply waits until it
receives an event. Once received, the listener
processes the event and then returns.
• The advantage of this design is that the
application logic that processes events is cleanly
separated from the user interface logic that
generates those events.
• A user interface element is able to “delegate” the
processing of an event to a separate piece of code.
5
6
• In the delegation event model, listener must
register with a source in order to receive an
event notification.
• Notification are sent only to listeners that
want to receive them.
• There are mainly three parts in delegation
event model.
– Events.
– Event sources.
– Event Listeners.
7
Components of Event Handling
• Events
An event is a change of state of an object.
• It can be generated as a consequence of a
person interacting with the elements in a
graphical user interface.
• Some of the activities that cause events to be
generated are pressing a button, entering a
character via the keyboard, selecting an
item in a list, and clicking the mouse.
8
Event
– Events may also occur that are not directly
caused by interactions with a user
interface.
– For example, an event may be generated
when a timer expires, a counter exceeds
a value, software or hardware failure
occurs, or an operation is completed.
• We are free to define events that are
appropriate for an application.
9
Event Sources
• A source is an object that generates an
event. This occurs when the internal state of
that object changes in some way.
• Sources may generate more than one type of
event.
• A source must register listeners in order for
the listeners to receive notifications about a
specific type of event.
• Each type of event has its own registration
method.
10
• Here is the general form to register listeners:
– public void addTypeListener(TypeListener el)
– For example: b.addActionListener(this);
• Here, type is the name of the event, and el is a
reference to the event listener.
• For example, the method that registers a
keyboard event listener is called
addKeyListener().
• The method that registers a mouse motion
listener is called addMouseMotionListener().
• When an event occurs, all registered listeners are
notified and receive a copy of the event object.
11
• The general form of unregister listener
method is this:
– Public void removeTypeListener(TypeListener el)
• Here, type is an object that is notified when
an event listener. For example, to remove a
keyboard listener, you would call
removeKeyListener()
12
Event Listeners
• A listener is an object that is notified when
an event occurs.
• It has two major requirements. First, it
must have been registered with one or more
sources to receive notifications about specific
types of events.
• Second, it must implement methods to
receive and process these notifications.
• The method that receive and process events
are defined in a set of interfaces found in
java.awt.event.
13
Event Listeners
• For example, the MouseMotionListener
interface defines two methods to receive
notifications when the mouse is dragged or
moved.
• Any object may receive and process one or
both of these events if it provides an
implementation of this interface.
14
15
Important Event Classes
and Interface
16
Event Classes
• The class AWTEvent, defined within the
java.awt package, is a subclass of EventObject.
• It is the superclass (either directly or indirectly)
of all AWT-based events used by the delegation
event model.
– EventObject is a superclass of all events.
– AWTEvent is a superclass of all AWT events
that are handled by the delegation event
model
17
Event Classes Description Listener Interface
ActionEvent generated when button is pressed, menu-item is ActionListener
selected, list-item is double clicked
MouseEvent generated when mouse is dragged, moved, clicked, MouseListener
pressed or released and also when it enters or exit a
component
KeyEvent generated when input is received from keyboard KeyListener
ItemEvent generated when check-box or list item is clicked ItemListener
TextEvent generated when value of textarea or textfield is TextListener
changed
MouseWheelEvent generated when mouse wheel is moved MouseWheelListener
WindowEvent generated when window is activated, deactivated, WindowListener
deiconified, iconified, opened or closed
ComponentEvent generated when component is hidden, moved, ComponentEventListe
resized or set visible ner
ContainerEvent generated when component is added or removed ContainerListener
from container
AdjustmentEvent generated when scroll bar is manipulated AdjustmentListener
FocusEvent generated when component gains or loses keyboard FocusListener
focus 18
• Steps to handle events:
– Implement interface in the class.
– Register the component with the listener.
19
Registration Methods
For registering the component with the Listener, many classes provide
the registration methods. For example:
Button
public void addActionListener(ActionListener a){}
MenuItem
public void addActionListener(ActionListener a){}
TextField
public void addActionListener(ActionListener a){}
public void addTextListener(TextListener a){}
TextArea
public void addTextListener(TextListener a){}
Checkbox
public void addItemListener(ItemListener a){}
Choice
public void addItemListener(ItemListener a){}
List
public void addActionListener(ActionListener a){}
public void addItemListener(ItemListener a){} 20
3.3 Adapter Classes
• Java adapter classes provide the default
implementation of listener interfaces.
• If you inherit the adapter class, you will not
be forced to provide the implementation of all
the methods of listener interfaces. So it saves
code.
21
java.awt.event Adapter classes
1) WindowAdapter
WindowListener
2) KeyAdapter
KeyListener
3) MouseAdapter
MouseListener
4) MouseMotionAdapter
MouseMotionListener
5) FocusAdapter
FocusListener
6) ComponentAdapter
ComponentListener
7) ContainerAdapter
ContainerListener
8)HierarchyBoundsAdapter
HierarchyBoundsListener
22
java.awt.dnd Adapter classes
1) DragSourceAdapter
DragSourceListener
2) DragTargetAdapter
DragTargetListener
23
javax.swing.event Adapter classes
MouseInputAdapter
MouseInputListener
InternalFrameAdapter
InternalFrameListener
24
WindowAdapter Example
import java.awt.*;
import java.awt.event.*;
public class AdapterExample {
// object of Frame
Frame f;
// class constructor
AdapterExample() {
// creating a frame with the title
f = new Frame ("Window Adapter");
// adding the WindowListener to the frame
// overriding the windowClosing() method
f.addWindowListener (new WindowAdapter() {
public void windowClosing (WindowEvent e) {
f.dispose();
25
}
});
// setting the size, layout and
f.setSize (400, 400);
f.setLayout (null);
f.setVisible (true);
}
// main method
public static void main(String[] args) {
new AdapterExample();
}
}
26
MouseAdapter Example
// importing the necessary libraries
import java.awt.*;
import java.awt.event.*;
// class which inherits the MouseAdapter class
public class MouseAdapterExample extends MouseAdapter {
// object of Frame class
Frame f;
// class constructor
MouseAdapterExample() {
// creating the frame with the title
f = new Frame ("Mouse Adapter");
// adding MouseListener to the Frame
f.addMouseListener(this);
// setting the size, layout and visibility of the frame
f.setSize (300, 300);
f.setLayout (null);
f.setVisible (true);
}
27
// overriding the mouseClicked() method of the MouseAdapter class
public void mouseClicked (MouseEvent e) {
// creating the Graphics object and fetching them from the Frame object using getGraphi
cs() method
Graphics g = f.getGraphics();
// setting the color of graphics object
g.setColor (Color.BLUE);
// setting the shape of graphics object
g.fillOval (e.getX(), e.getY(), 30, 30);
}
// main method
public static void main(String[] args) {
new MouseAdapterExample();
}
}
28
MouseMotionAdapter Example
import java.awt.*;
import java.awt.event.*;
// class which inherits the MouseMotionAdapter class
public class MouseMotionAdapterExample extends MouseMotionAdapter {
// object of Frame class
Frame f;
// class constructor
MouseMotionAdapterExample() {
// creating the frame with the title
f = new Frame ("Mouse Motion Adapter");
// adding MouseMotionListener to the Frame
f.addMouseMotionListener (this);
// setting the size, layout and visibility of the frame
f.setSize (300, 300);
f.setLayout (null);
f.setVisible (true); 29
}
// overriding the mouseDragged() method
public void mouseDragged (MouseEvent e) {
// creating the Graphics object and fetching them from the Frame object using getGraphi
cs() method
Graphics g = f.getGraphics();
// setting the color of graphics object
g.setColor (Color.ORANGE);
// setting the shape of graphics object
g.fillOval (e.getX(), e.getY(), 20, 20);
}
public static void main(String[] args) {
new MouseMotionAdapterExample();
}
}
30
import java.awt.*;
import java.awt.event.*;
public class KeyAdapterExample extends KeyAdapter {
// creating objects of Label, TextArea and Frame
Label l;
TextArea area;
Frame f;
KeyAdapterExample() {
f = new Frame ("Key Adapter");
l = new Label();
l.setBounds (20, 50, 200, 20);
area = new TextArea();
area.setBounds (20, 80, 300, 300);
31
area.addKeyListener(this);
f.add(l);
f.add(area);
f.setSize (400, 400);
f.setLayout (null);
f.setVisible (true);
}
public void keyReleased (KeyEvent e) {
String text = area.getText();
String words[] = text.split ("\\s");
l.setText ("Words: " + words.length + " Characters:" + text.length());
}
public static void main(String[] args) {
new KeyAdapterExample();
}
}
32
3.5 Event Listener
• Changing the state of an object is known as an event. For
example, click on button, dragging mouse etc.
• The java.awt.event package provides many event classes
and Listener interfaces for event handling.
Java event handling by implementing ActionListener
import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
//register listener
b.addActionListener(this);//passing current instance
34
//add components and set size, layout and visibility
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
public static void main(String args[]){
new AEvent();
}
35
}
public void setBounds(int xaxis, int yaxis, int width, int
height); have been used in the above example that sets
the position of the component it may be button, textfield
etc.
36
ActionListener Interface
The Java ActionListener is notified whenever you click on
the button or menu item. It is notified against
ActionEvent.
The ActionListener interface is found in java.awt.event
package.
It has only one method: actionPerformed().
37
actionPerformed() method
The actionPerformed() method is invoked
automatically whenever you click on the registered
component.
public void actionPerformed(ActionEvent e);
38
How to write ActionListener
The common approach is to implement the ActionListener. If you implement the
ActionListener class, you need to follow 3 steps:
1) Implement the ActionListener interface in the class:
public class ActionListenerExample Implements ActionListener
2) Register the component with the Listener:
component.addActionListener(instanceOfListenerclass);
3) Override the actionPerformed() method:
public void actionPerformed(ActionEvent e){
//Write the code here
}
39
Java ActionListener Example: On Button click
import java.awt.*;
import java.awt.event.*;
//1st step
public class ActionListenerExample implements ActionListener{
public static void main(String[] args) {
Frame f=new Frame("ActionListener Example");
TextField tf=new TextField();
tf.setBounds(50,50, 150,20);
Button b=new Button("Click Here");
b.setBounds(50,100,60,30);
40
//2nd step
b.addActionListener(this);
f.add(b);f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
//3rd step
public void actionPerformed(ActionEvent e){
tf.setText("Welcome to Javatpoint.");
}
}
41
Java ItemListener Interface
• The Java ItemListener is notified whenever you
click on the checkbox.
• It is notified against ItemEvent.
• The ItemListener interface is found in
java.awt.event package.
• It has only one method: itemStateChanged().
42
itemStateChanged() method
The itemStateChanged() method is invoked automatically
whenever you click or unclick on the registered checkbox
component.
public abstract void itemStateChanged(ItemEvent e);
43
Java ItemListener Example:-
import java.awt.*;
import java.awt.event.*;
public class ItemListenerExample implements ItemListener{
Checkbox checkBox1,checkBox2;
Label label;
ItemListenerExample(){
Frame f= new Frame("CheckBox Example");
label = new Label();
label.setAlignment(Label.CENTER);
label.setSize(400,100);
checkBox1 = new Checkbox("C++");
checkBox1.setBounds(100,100, 50,50);
checkBox2 = new Checkbox("Java");
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1); f.add(checkBox2); f.add(label);
checkBox1.addItemListener(this);
checkBox2.addItemListener(this);
44
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public void itemStateChanged(ItemEvent e) {
if(e.getSource()==checkBox1)
label.setText("C++ Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
if(e.getSource()==checkBox2)
label.setText("Java Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
public static void main(String args[])
{
new ItemListenerExample();
}
}
45
Key Listener
• The Java KeyListener is notified whenever you
change the state of key. It is notified against
KeyEvent.
• The KeyListener interface is found in
java.awt.event package, and it has three methods.
Interface declaration
Following is the declaration for java.awt.event.KeyListener interface:
implements KeyListener
46
Methods of KeyListener interface
1.public abstract void keyPressed (KeyEvent e);
It is invoked when a key has been pressed.
2.public abstract void keyReleased (KeyEvent e);
It is invoked when a key has been released.
3.public abstract void keyTyped (KeyEvent e);
It is invoked when a key has been typed.
47
KeyListener Example
import java.awt.*;
import java.awt.event.*;
public class KeyListenerExample extends Frame implements KeyListener {
Lael l;
TextArea area;
KeyListenerExample() {
// creating the label
l = new Label();
l.setBounds (20, 50, 100, 20);
area = new TextArea();
area.setBounds (20, 80, 300, 300);
area.addKeyListener(this);
add(l);
add(area);
setSize (400, 400);
setLayout (null);
setVisible (true);
}
48
public void keyPressed (KeyEvent e) {
l.setText ("Key Pressed");
}
public void keyReleased (KeyEvent e) {
l.setText ("Key Released");
}
public void keyTyped (KeyEvent e) {
l.setText ("Key Typed");
}
public static void main(String[] args) {
new KeyListenerExample();
}
}
49
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ContainerEventExample
{
public static void main(String args[])
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contentPane = frame.getContentPane();
ContainerListener cont = new ContainerListener()
{
ActionListener listener = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.out.println("Selected: " + e.getActionCommand());
}
}; 50
public void componentAdded(ContainerEvent e)
{
Component c = e.getChild();
if (c instanceof JButton)
{
JButton b = (JButton) c;
b.addActionListener(listener);
}
}
public void componentRemoved(ContainerEvent e)
{
Component c = e.getChild();
if (c instanceof JButton)
{
JButton b = (JButton) c;
b.removeActionListener(listener);
}
}
};
51
MouseListener Interface
The Java MouseListener is notified whenever you change the state of
mouse. It is notified against MouseEvent.
The MouseListener interface is found in java.awt.event package. It has
five methods.
Methods of MouseListener interface
public abstract void mouseClicked(MouseEvent e);
public abstract void mouseEntered(MouseEvent e);
public abstract void mouseExited(MouseEvent e);
public abstract void mousePressed(MouseEvent e);
public abstract void mouseReleased(MouseEvent e);
52
MouseListener Example
import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample extends Frame implements MouseListener{
Label l;
MouseListenerExample(){
addMouseListener(this);
l=new Label();
l.setBounds(20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e) {
l.setText("Mouse Clicked");
}
53
public void mouseEntered(MouseEvent e) {
l.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e) {
l.setText("Mouse Exited");
}
public void mousePressed(MouseEvent e) {
l.setText("Mouse Pressed");
}
public void mouseReleased(MouseEvent e) {
l.setText("Mouse Released");
}
public static void main(String[] args) {
new MouseListenerExample();
}
}
54
MouseMotionListener Interface
The Java MouseMotionListener is notified whenever you move or drag mouse.
It is notified against MouseEvent
The MouseMotionListener interface is found in java.awt.event package. It has
two methods.
Methods of MouseMotionListener interface
The signature of 2 methods found in MouseMotionListener interface are given
below:
1) public abstract void mouseDragged(MouseEvent e);
2) public abstract void mouseMoved(MouseEvent e);
55
MouseMotionListener Example
import java.awt.*;
import java.awt.event.*;
public class MouseMotionListenerExample extends Frame implements MouseMotionListener{
MouseMotionListenerExample(){
addMouseMotionListener(this);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseDragged(MouseEvent e) {
Graphics g=getGraphics();
g.setColor(Color.BLUE);
g.fillOval(e.getX(),e.getY(),20,20);
}
public void mouseMoved(MouseEvent e) {}
public static void main(String[] args) {
new MouseMotionListenerExample();
}
}
56
TextListener Interface
• The class which processes the TextEvent should
implement this interface.
• The object of that class must be registered with a
component.
• The object can be registered using the
addTextListener() method.
• Methods
• void textValueChanged(TextEvent e)
• Invoked when the value of the text has changed.
57
import java.awt.*;
import java.awt.event.*;
public class TextEventEx1 implements TextListener
{
Label label1, label2;
TextField field1;
Frame jf;
String str;
TextEventEx1()
{
jf = new Frame("Handling TextEvent");
label1= new Label("Type in the textfield, to see the textevents it
generates -", Label.CENTER);
label2= new Label(); field1 = new TextField(25);
jf.setLayout(new FlowLayout());
58
jf.add(label1);
jf.add(field1);
jf.add(label2);
field1.addTextListener(this);
jf.setSize(340,200);
jf.setVisible(true);
}
public void textValueChanged(TextEvent te) {
label2.setText(te.paramString());
jf.setVisible(true);
}
public static void main(String... ar)
{
new TextEventEx1();
}
59
Summary of Event Classes &
Listeners
60
61
62
63
64