Event Handling Notes
Event Handling Notes
Event Handling Notes
Event Handling
12 Marks
1
Event Handling
Any program that uses GUI (graphical user
interface) such as Java application written for
windows, is event driven.
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
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.
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().
11
• The general form of unregister listener
method is this:
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
18
• Steps to handle events:
– Implement appropriate 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
ActionEvent
• An ActionEvent is generated when a button is
pressed, a list item is double-clicked, or a menu item
is selected.
• The ActionEvent class defines four integer constants that are
used to identify modifiers associated with an action event:
• public static final int ALT_MASK The alt modifier.
– An indicator that the alt key was held down during the event.
• public static final int SHIFT_MASK The shift modifier.
– An indicator that the shift key was held down during the event.
• public static final int CTRL_MASK The control modifier.
– An indicator that control key was held down during the event.
• public static final int META_MASK The meta modifier.
– An indicator that the meta key was held down during the
event. (The Meta key is a modifier key on certain keyboards)
Methods
• public String getActionCommand()
– Returns the command string associated with this
action.
• int getModifiers()
– Returns the modifier keys held down during this
action event.
• String paramString()
– Returns a parameter string identifying this action
event. 22
ActionListener Interface
23
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
if(action.equals("Ok"))
actionMessage = "Ok Button Pressed";
else if(action.equals("Cancel"))
actionMessage = "Cancel Button Pressed";
repaint();
}
}
25
26
ItemEvent class
• A semantic event which indicates that an item was
selected or deselected.
• This high-level event is generated by an ItemSelectable
object (such as a List) when an item is selected or
deselected by the user.
• This class has following constants.
• public static final int SELECTED
– This state-change value indicates that an item was
selected.
• public static final int DESELECTED
– This state-change-value indicates that a selected
item was deselected
27
Methods of ItemEvent Class
• public ItemSelectable getItemSelectable()
– Returns the creator of the event.
– Returns: the ItemSelectable object that originated the event.
• public Object getItem()
– Returns the item affected by the event.
– Returns: the item (object) that was affected by the event.
• public int getStateChange()
– Returns the type of state change (selected or deselected).
– Returns: an integer that indicates whether the item was selected or
deselected
28
• public ItemEvent (ItemSelectable source, int id, Object item,
int stateChange)
– Constructs an ItemEvent object.
– Parameters:
– source - the ItemSelectable object that originated the
event
– id - an integer that identifies the event type
– item - an object -- the item affected by the event
– stateChange - an integer that indicates whether the
item was selected or deselected
29
ItemListener interface
• void itemStateChanged(ItemEvent e)
• Invoked when an item has been selected or
deselected by the user.
• The code written for this method performs the
operations that need to occur when an item is
selected (or deselected).
30
Checkbox
• Checkbox control is used to turn an option on(true)
or off(false). There is label for each checkbox
representing what the checkbox does.
Chapter No 1 -AWT 31
Constructor
1 Checkbox()
Creates a check box with an empty string for its label.
2 Checkbox(String label)
Creates a check box with the specified label.
3 Checkbox(String label, boolean state)
Creates a check box with the specified label and sets the specified state.
Chapter No 1 -AWT 32
Method
1 String getLabel()
Gets the label of this check box.
2 boolean getState()
Determines whether this check box is in the on or off state.
Chapter No 1 -AWT 33
Event Handling
• Event
ItemEvent
• Interface/EventHandler/Listener
ItemListener
• Method
• Public Void itemStateChanged(ItemEvent obj)
Chapter No 1 -AWT 34
/*
<applet code="checkbox" width=300
height=100>
</applet>
*/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class checkbox extends Applet
{
35
myCheckbox1 = new MyCheckbox("Item 1");
add(myCheckbox1);
myCheckbox2 = new MyCheckbox("Item 2");
add(myCheckbox2);
myCheckbox3 = new MyCheckbox("Item 3");
add(myCheckbox3);
myCheckbox4 = new MyCheckbox("Item 4");
add(myCheckbox4);
}
class MyCheckbox extends Checkbox
{
public MyCheckbox(String label)
{
super(label);
enableEvents(AWTEvent.ITEM_EVENT_MASK);
}
protected void processItemEvent(ItemEvent ie)
{
showStatus("Checkbox name " + getLabel() +
getState());
super.processItemEvent(ie);
}
} 36
List
• The List represents a list of text items. The list can be
configured that user can choose either one item or
multiple items.
Chapter No 1 -AWT 37
Class constructors
1 List()
Creates a new scrolling list.
2 List(int rows)
Creates a new scrolling list initialized with the specified number of
visible lines.
3 List(int rows, boolean multipleMode)
Creates a new scrolling list initialized to display the specified number of
rows.
Chapter No 1 -AWT 38
Class methods
1 void add(String item)
Adds the specified item to the end of scrolling list.
2 void add(String item, int index)
Adds the specified item to the the scrolling list at the position indicated
by the index.
Chapter No 1 -AWT 39
Event Handling
• Event
ItemEvent
• Interface/EventHandler/Listener
ItemListener
• Method
• Public void itemStateChanged(ItemEvent obj)
Chapter No 1 -AWT 40
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);
f.setSize(400,400);
41
f.setLayout(null);
f.setVisible(true);
}
public void itemStateChanged(ItemEvent e) {
if(e.getSource()==checkBox1)
label.setText("C++ Checkbox: "
+
(e.getStateChange()==1?"checked":"unchecke
d"));
if(e.getSource()==checkBox2)
label.setText("Java Checkbox: "
+
(e.getStateChange()==1?"checked":"unchecke
d"));
}
public static void main(String args[])
{
new ItemListenerExample();
}
}
42
KeyEvent class
• An event which indicates that a keystroke
occurred in a component.
• This class has following constant.
• public static final int KEY_PRESSED
– This event is generated when a key is pushed down.
• public static final int KEY_RELEASED
– This event is generated when a key is let up.
• public static final int KEY_TYPED
– This event is generated when a character is entered. In the
simplest case, it is produced by a single key press.
43
Methods of KeyEvent class
• public int getKeyCode()
– Returns the integer keyCode associated with the key in
this event.
– Returns: the integer code for an actual key on the
keyboard.
• public char getKeyChar()
– Returns the character associated with the key in this
event.
– For example, the KEY_TYPED event for shift + "a"
returns the value for "A".
• boolean isActionKey()
– Returns true if the key firing the event is an action key.
Examples of action keys include Page Up, Caps Lock,
the arrow and function keys.
44
KeyListener Interface
• Key events indicate when the user is typing at the
keyboard.
45
• The first kind of event is called a key-typed event.
– To know when the user types a Unicode character ? whether
by pressing one key such as 'a' or by pressing several keys in
sequence ?
46
Methods of KeyListener Interface
Method Purpose
keyTyped(KeyEvent) Called just after the user types a
Unicode character into the listened-to
component.
keyPressed(KeyEvent) Called just after the user presses a key
while the listened-to component has
the focus.
keyReleased(KeyEvent) Called just after the user releases a
key while the listened-to component
has the focus.
47
• import java.awt.*;
• import java.awt.event.*;
• public class KeyListenerExample extends Frame implements KeyListener {
• Label l;
TextArea area;
• KeyListenerExample() {
• l = new Label();
48
• add(l);
• add(area);
• setSize (400, 400);
• setLayout (null);
• setVisible (true);
• }
• public void keyPressed (KeyEvent e) {
• l.setText ("Key Pressed");
49
• 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();
• }
• }
50
TextEvent class
• A semantic event which indicates that an object's text
changed.
• This high-level event is generated by an object (such as a
TextComponent) when its text changes.
• void textValueChanged(TextEvent e)
• Invoked when the value of the text has
changed.
• The code written for this method performs
the operations that need to occur when text
changes.
52
• import java.awt.*;
• import java.awt.event.*;
• tf1=new TextField(15);
• tf2=new TextField(5);
• tf3=new TextField(5);
53
• p1.add(l1);
• p1.add(tf1);
• p1.add(l2);
• p1.add(tf2);
• p1.add(l3);
• p1.add(tf3);
• add("North",p1);
•
• tf1.addTextListener(this);
• tf2.addTextListener(this);
• tf3.addTextListener(this);
• }
54
public void paint(Graphics g)
{
setFont(newFont("TimesRoman",Font.BOLD,30));
g.setColor(Color.red);
g.drawString("Name"+nm,x,y);
}
public static void main(String args[])
{
TextEventEx t=new TextEventEx();
Toolkit tx=Toolkit .getDefaultToolkit();
t.setSize(tx.getScreenSize());
t.setVisible(true);
}
}
55
WindowEvent class
• A low-level event indicates that a window has
changed its status.
56
int constants
• WINDOW_ACTIVATED
• WINDOW_CLOSED
• WINDOW_CLOSING
• WINDOW_DEACTIVATED
• WINDOW_DEICONIFIED
• WINDOW_GAINED_FOCUS
• WINDOW_ICONIFIED
• WINDOW_LOST_FOCUS
• WINDOW_OPENED
• WINDOW_STATE_CHANGED
57
Constructors
• public WindowEvent(Window source,int id)
– Constructs a WindowEvent object.
– Parameters: source - the Window object that originated the event
– id - an integer indicating the type of event
• - public WindowEvent(Window source,int id,Window opposite,int oldState,
int newState)
– Note that passing in an invalid id results in unspecified behavior. This
method throws an IllegalArgumentException if source is null.
– source - the Window object that originated the event
– id - an integer indicating the type of event.
– opposite - the other window involved in the focus or activation change,
or null
– oldState - previous state of the window for window state change event
– newState - new state of the window for window state change event
58
• public Window getWindow()
– Returns the originator of the event.
– Returns: the Window object that originated the
event
59
WindowListener interface
• void windowOpened(WindowEvent e)
– Invoked the first time a window is made visible.
• void windowClosing(WindowEvent e)
– Invoked when the user attempts to close the window from the window's
system menu.
• void windowClosed(WindowEvent e)
– Invoked when a window has been closed as the result of calling dispose on
the window
• void windowIconified(WindowEvent e)
– Invoked when a window is changed from a normal to a minimized state.
For many platforms, a minimized window is displayed as the icon specified
in the window's iconImage property.
• void windowDeiconified(WindowEvent e)
– Invoked when a window is changed from a minimized to a normal state.
• void windowActivated(WindowEvent e)
– Invoked when the Window is set to be the active Window.
• void windowDeactivated(WindowEvent e)
– Invoked when a Window is no longer the active Window.
60
WindowFocusListener interface
• The listener interface for receiving WindowEvents, including
WINDOW_GAINED_FOCUS and WINDOW_LOST_FOCUS
events.
• void windowGainedFocus(WindowEvent e)
– Invoked when the Window is set to be the focused Window, which
means that the Window, or one of its subcomponents, will receive
keyboard events.
• void windowLostFocus(WindowEvent e)
– Invoked when the Window is no longer the focused Window, which
means that keyboard events will no longer be delivered to the
Window or any of its subcomponents.
61
MouseEvent class
This event indicates a mouse action occurred in a
component. This low-level event is generated by a
component object for Mouse Events and Mouse
motion events.
62
Constants for java.awt.event.MouseEvent class:
65
MouseListener Interface
• Mouse events notify when the user uses the mouse (or
similar input device) to interact with a component.
66
Methods of MouseListener Interface
Method Purpose
mouseClicked(MouseEvent) Called just after the user clicks the
listened-to component.
mouseEntered(MouseEvent) Called just after the cursor enters the
bounds of the listened-to component.
mouseExited(MouseEvent) Called just after the cursor exits the
bounds of the listened-to component.
mousePressed(MouseEvent) Called just after the user presses a
mouse button while the cursor is over
the listened-to component.
mouseReleased(MouseEvent) Called just after the user releases a
mouse button after a mouse press over
the listened-to component.
67
MouseMotionListener Interface
• Mouse-motion events notify when the user uses the mouse (or a
similar input device) to move the onscreen cursor.
68
Methods of MouseMotionListener Interface
Method Purpose
69
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
70
public void paint(Graphics g) // draw message to screen
{
super.paint(g);
repaint();
71
}
public void mouseClicked(MouseEvent e) // save coordinates of clicks
{
x = e.getX();
y = e.getY();
event = "click";
repaint();
}
repaint();
}
72
public void mouseEntered(MouseEvent e) // save coordinates when mouse
enters applet
{
x = e.getX();
y = e.getY();
event = "enter";
repaint();
}
repaint();
}
}
/*<applet code=MouseEventDemo height=300 width=300></applet>*/ 73
Adapter Classes
• Java provides a special feature, called an adapter class that can simplify
• the creation of event handlers in certain situations. An adapter class
provides
• an empty implementation of all methods in an event listener interface.
Adapter
• classes are useful when we want to receive and process only some of the
• events that are handled by a particular event listener interface. We can
define a
• new class to act as an event listener by extending one of the adapter
classes
• and implementing only those events in which we are interested. For
example,
• the MouseMotionAdapter class has two methods, mouseDragged( ) and
• mouseMoved( ).
74
THANK YOU
75