BSC 2ndsem Java Lecture 11 Event Handling
BSC 2ndsem Java Lecture 11 Event Handling
The Delegation Event Model has the following key participants namely:
// Display keystrokes.
public void paint(Graphics g)
{
g.drawString(msg, X, Y);
}
}
Question: What if you wish
to know if a special key like
function key or arrow key is
pressed?
It is to be handled in
keyPressed method.
To handle special keys
To handle the special keys, such as the arrow or
function keys, you need to respond to them within
the keyPressed( ) handler. They are not available
through keyTyped( ).
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="KeyEvents" width=300 height=100>
</applet>
*/
33
Continued..
public class KeyEvents extends Applet
implements KeyListener {
String msg = "";
int X = 10, Y = 20; // output coordinates
public void init() {
addKeyListener(this);
}
34
Continued..
public void keyPressed(KeyEvent ke) {
showStatus("Key Down");
int key = ke.getKeyCode();
switch(key) {
case KeyEvent.VK_F1:
msg += "<F1>";
break;
case KeyEvent.VK_F2:
msg += "<F2>";
break;
35
Continued..
case KeyEvent.VK_F3:
msg += "<F3>";
break;
case KeyEvent.VK_PAGE_DOWN:
msg += "<PgDn>";
break;
case KeyEvent.VK_PAGE_UP:
msg += "<PgUp>";
break;
36
Continued..
case KeyEvent.VK_LEFT:
msg += "<Left Arrow>";
break;
case KeyEvent.VK_RIGHT:
msg += "<Right Arrow>";
break;
}
repaint();
}
37
Continued..
public void keyReleased(KeyEvent ke) {
showStatus("Key Up");
}
public void keyTyped(KeyEvent ke) {
msg += ke.getKeyChar();
repaint();
}
// Display keystrokes.
public void paint(Graphics g) {
g.drawString(msg, X, Y);
}
}
38
Sample Output
39
Program to Add a Button to a Frame
import java.awt.*;
import java.awt.event.*;
public class ButtonText {
public static void main(String[] args) {
Frame frame=new Frame("Button Frame");
Button button = new Button("Submit");
frame.add(button);
frame.setLayout(new FlowLayout());
frame.setSize(200,100);
frame.setVisible(true);
49
Continued..
• Note: MouseAdapter also provides an empty
implementation for MouseMotionListener.
However, for the sake of illustration, this example
handles each separately.
50
Continued..
// Demonstrate an adapter.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="AdapterDemo" width=300
height=100>
</applet>
*/
51
Continued..
public class AdapterDemo extends Applet {
public void init() {
// register listener
addMouseListener (new MyMouseAdapter(this));
addMouseMotionListener (new
MyMouseMotionAdapter(this));
}
}
Note: Here Applet class does not implements listener
class. Implication??
Event Source and Event Listener are different.
52
Continued..
class MyMouseAdapter extends MouseAdapter {
AdapterDemo adapterDemo;
// constructor
public MyMouseAdapter(AdapterDemo
adapterDemo) {
this.adapterDemo = adapterDemo;
}
// Handle mouse clicked.
public void mouseClicked(MouseEvent me) {
adapterDemo.showStatus ("Mouse clicked");
}
}
53
Continued..
class MyMouseMotionAdapter extends
MouseMotionAdapter {
AdapterDemo adapterDemo;
public MyMouseMotionAdapter(AdapterDemo
adapterDemo) {
this.adapterDemo = adapterDemo;
}
// Handle mouse dragged.
public void mouseDragged(MouseEvent me) {
adapterDemo.showStatus("Mouse dragged");
}
} 54
Inner Classes
Not having to implement all of the methods defined
by the MouseMotionListener and MouseListener
interfaces saves a considerable amount of effort.
55
Use of Inner Class
• Here, InnerClassDemo is a top-level class that extends
Applet.
• MyMouseAdapter is an inner class that extends
MouseAdapter.
• Because MyMouseAdapter is defined within the scope of
InnerClassDemo, it has access to all of the variables and
methods within the scope of that class. Therefore, the
mousePressed( ) method can call the showStatus( ) method
directly.
• It no longer needs to do this via a stored reference to the
applet. Thus, it is no longer necessary to pass
MyMouseAdapter( ) a reference to the invoking object.
56
Source Code
import java.applet.*;
import java.awt.event.*;
/* <applet code="InnerClassDemo" width=200 height=100>
</applet> */
public class InnerClassDemo extends Applet {
public void init() {
addMouseListener(new MyMouseAdapter());
}
class MyMouseAdapter extends MouseAdapter {
public void mousePressed(MouseEvent me) {
showStatus("Mouse Pressed");
}
}
}
57
Anonymous Inner Class
A class that has no name is known as anonymous
inner class in java. It should be used if you have to
override method of class or interface. Java
Anonymous inner class can be created by two ways:
1. Using Class (may be abstract or concrete).
2. Using Interface
1.Java anonymous inner class example using class
abstract class Person{
abstract void eat();
}
95-712 OOP Java 58
Continued..
class TestAnonymousInner{
public static void main(String args[]){
Person p=new Person(){
void eat(){System.out.println("nice fruits");}
};
p.eat();
}
}
/* <applet code="AnonymousInnerClassDemo"
width=200 height=100> </applet>
*/
95-712 OOP Java 63
Continued..
public class AnonymousInnerClassDemo extends
Applet {
public void init() {
addMouseListener (new MouseAdapter() {
public void mousePressed(MouseEvent me) {
showStatus("Mouse Pressed");
}
}); // header closed
}
}
64
Continued..
• The classAnonymousInnerClassDemo extends
Applet class.
an ActionListener that is
registered with the
UPPER Button
• ActionListener handles public class Handler implements
ActionListener
in actionPerformed {
method. public void
actionPerformed(ActionEvent e){
System.out.println(“Handling “ +
e);
}
}
Events
• An event is an object that describes a state
change in a source.
• 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.
• Events may also occur that are not directly
caused by interactions with a user interface.
• Eg. an event may be generated when a timer
expires, a counter exceeds a value etc.
• You can define your own application specific
events.
Events and Event Objects
• Since events may be of different types but still
exhibit some shared traits (inheritance) Java represents
the event classes in a hierarchy.
Some classes and Object
methods in the event EventObject
hierarchy.
AWTEvent
ActionEvent ComponentEvent
String getActionCommand()
InputEvent WindowEvent
MouseEvent
KeyEvent
int getX()
char getKeyChar()
74
Event handling usually involves three types of
objects
• Objects that are used to hold and report
information about the event.
• Objects that are typically the source of
events.
• Objects, called listeners, are used to handle
events.
A mouse Example
object
Event data and methods
An event object
Event Source that describes,
say, the x and y
coordinate of
where the mouse Event Listener
was clicked
The listener object
has methods that
are called for
particular events
76
A mouse Example
object
An event object
Implements
that describes,
MouseListener
say, the x and y
coordinate of
where the mouse
A mouse object must was clicked
be told who its listener The listener object
is. has methods that
are called for
The event object is sent particular events
to a listener method
77
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.
• Some general Event Sources are: Button,
CheckBox,List,MenusItem,Window,TextItems
Etc…
Continued..
Event Source Description
Button Generates action events when the button is pressed.
Check box Generates item events when the check box is selected
or deselected.
Choice Generates item events when the choice is changed.
List List Generates action events when an item is double-
clicked; generates item events when an item is
selected or deselected.
Menu item Generates action events when a menu item is
selected; generates item events when a checkable
menu item is selected or deselected.
Scroll bar Generates adjustment events when the scroll bar is
manipulated.
Text components Generates text events when the user enters a
character.
Window Generates window events when a window is
Continued..
• In addition to these graphical user interface
elements, any class derived from Component,
such as Applet, can generate events.
• For example, you can generate key and mouse
events from an applet.
• Similarly generated events can be received by
applets.
• In applets, an applet can be both source and
listener.
• You may also build your own components that
generate events.
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 methods that receive and process events are
defined in a set of interfaces, such as those found in
java.awt.event package.
• .
Listeners are Interfaces
Remember what an interface provides? If
class X implements an interface then class X
promises to provide (at least) the methods
declared in the interface.
Eg. the MouseMotionListener interface, that
defines two methods to receive notifications
when the mouse is dragged or moved
88
continued
89
Inheritance tree of applets & frames
Object
Component
Canvas
Label Container
List
Button
TextComponent
Choice
91