CH 4 - Event
CH 4 - Event
CH
3
Event Handling
1
The Event Delegation Model
The main difference between application and applet is applications
provide console applications while Applets provides GUI. No doubt this is the
difference between applications and applets but the other difference is GUI
based programs are event-driven while applications are not.
Our applets are also event-driven. That is the code to handle a particular
type of event is invoked only when such an event occurs.
The java runtime system notifies the applet about an event by calling an
event handler that has been supplied by the applet. Upon receipt of the event, the
applet handles the event and then returns control to the run-time system.
There are various ways in which an event-driven interface can be defined,
and the specific mechanism is determined by the event model. Java
Development Kit (JDK 1.1) introduces the delegation event model.
This model provides an efficient way for an event to be sent from a source
to one or more listeners. This model also provides a standard mechanism for a
source to generate an event and send it to a set of listeners.
What is Event?
An event is an object that describes some state change in a source. It can
be generated when a person interacts with an element in a GUI. For example,
pressing a button, clicking the mouse, double clicking on a list box entry, or
closing a window.
A source generates events. It has mainly three responsibilities.
First, it must provide methods that allow listeners to register and unregister
for notifications about a specific type of event.
Second, it must generate the event.
And finally, it must send the event to all the registered listeners.
Sometimes it may happen that a source may generate several types of events in
that case multiple methods would be provided.
We can add / remove the listener in the following way :
(1)public void addTypeListner(TypeListner el)
(2)public void removeTypeListener(TypeListener el)
Here the type is the type of the event and el is the event listener.
What is The Listener?
The listener receives event notifications. It has three main responsibilities.
First, it must register to receive notifications about specific events. It is possible
by calling the appropriate registration method of the source. Second it must
implement an interface to receive events of that type. And finally, it must
unregister if it no longer wants to receive those notifications.
The Event Delegation Model can be described through the following
figure.
2
The Event Delegation Model
Event Listeners
The java.util.EventListener interface does not define any constants
or methods but exists only to identify those interfaces that process events. All
event listeners interface must extends this interface. Various listeners for the
various events are summarized in the following table.
Remember that all the listeners are defined in java.awt.event package.
Event Class Listener Interface
ActionEvent ActionListener
AdjustmentEvent AdjustmentListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
ItemEvent ItemListener
KeyEvent KeyListener
4
MouseEvent MouseListener, MouseMotionListener
TextEvent TextListener
WindowEvent WindowListener
5
Source of Events
Event Source Description
Button Generates action events when the button is
pressed.
Checkbox generates item events when the check box is
selected or deselected
Choice Generate item events when the choice is changed
List Generate action when events an item is double
clicked; generate item events when an item is
selected or deselected.
scrollbar generate adjustment events when the scroll bar is
manipulated.
text components generate text events when the user enters a
characters
window generates window events when a window is
activated, close, deactivated, deiconified etc.
6
Event Class
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 interger constants that can be used to
identify any modifiers associated with an action event. ALT_MASK,
CTRL_MASK, META_MASK and SHIFT_MASK.
In addition, there is an integer constant, ACTION_PERFORMED, which
can be used to identify action events.
ActionEvent has these 2 constructors:
o ActionEvent(Object src, int type, String cmd)
o ActionEvent(Object src, int type String cmd, int modifiers)
Here src is a reference to the object that generated this event. The type of
the event is specified by type, and its command string is cmd. The
argument modifiers indicates which modifier keys (ALT, CTRL, META
and/or SHIFT) were pressed when the event was generated.
Obtain command name for the invoking ActionEvent object by using
getActionCommand( ) method.
The getModifiers( ) method returns a value that indicates which modifiers
key(ALT, CTRL, META, and/or SHIFT) were pressed when the event was
generated. Its form is shown here: int getModifiers( )
AdjustmentEvent Class
The AdjustmentEvent is generated by a scroll bar. There are five of adjustment events. The
AdjustmentEvent class defines integer constants that can be used to identify them. The constants and
their meanings are shown here
BLOCK_DECREMENT the user clicked inside the scroll bar to
decrease its value.
BLOCK_INCREMENT the user clicked inside the scroll bar to
increment its value.
TRACK the slider was dragged
ItemEvent
An ItemEvent is generated when a check box or list item is clicked or
when a checkable menu item is selected or deselected.
The integer Constants of ItemEvent:-
o DESELECTED:- The user deselect an item.
o SELECT:- the user select an item.
In addition, ItemEvent defines one interger constant,
ITEM_STATE_CHANGED, which signifies a change of state. ItemEvent
constructor:
o ItemEvent(ItemSelectable src, int type, Object entry, int state)
Here, src is a reference to the component that generated this event.
Method:
Object getItem()
Returns the item affected by the event.
ItemSelectable getItemSelectable()
(Interface) Returns the originator of the event.
int getStateChange()
Returns the type of state change (selected or
deselected).
String paramString()
Returns a parameter string identifying this item event.
ComponentEvent Class
A componentEvent is generated when the resize, position or visibility of
component is changed. There are 4 types of component events.
The ComponentEvent class defines integer constants that can be used to identify them. The constants
and their meaning are shown here.
COMPONENT_HIDDEN The Component was hidden
COMPONENT_MOVED The component was moved.
COMPONENT_RESIZED The component was resized.
COMPONENT_SHOWN the component became visible.
Constructor: ComponentEvent(Component src, int type)
Here, src is a reference to the object that generate this event. The type of the
event is specified by type.
8
ComponentEvent is the superclass either directly or indirectly of
ContainerEvent, FoucsEvent, KeyEvent, MouseEvent and WindowEvent.
Method:
Container getContainer( ) obtain reference to the container that
generated this event by using this
method.
Component getChild( ) returns a reference to the component
that was added to or removed from the
container
FocusEvent
A FocusEvent is generated when a component gain or loses input focus.
These events are identified by the integer constants FOCUS_GAINED
AND FOCUS_LOST.
FoucsEvent is a subclass of CompomentEvent and has these constructors.
o FocusEvent(Comonent src, int type)
o FocusEvent(Component src, int type, Boolean temporary flag)
Here, src is a reference to the component that generated this event. The
type fo the event is specified by type. The argument temporary flag is set
to true if the focus event is temporary. Otherwise is set to false.
Method:
boolea isTemporary()
n Identifies the focus change event as temporary.
MouseEvent
There are 7 types of mouse events. The MouseEvent class defines the
following integer constants that can be used to identify them.
MOUSE_CLICKED The "mouse clicked" event.
MOUSE_DRAGGED The "mouse dragged" event.
MOUSE_ENTERED The "mouse entered" event.
MOUSE_EXITED The "mouse exited" event.
MOUSE_MOVED The "mouse moved" event.
MOUSE_PRESSED The "mouse pressed" event.
MOUSE_RELEASED The "mouse released" event.
MouseEvent is a subclass of InputEvent and has this constructuor.
MouseEvent(Component src, int type, long when, int modifiers, int x, int
y, int clicks, boolean triggersPopup)
source - the Component that originated the event
id - the integer that identifies the event
when - a long int that gives the time the event occurred
modifiers - the modifier keys down during event (e.g. shift, ctrl, alt, meta) Either
extended _DOWN_MASK or old _MASK modifiers should be used, but both
9
models should not be mixed in one event. Use of the extended modifiers is
preferred.
x - the horizontal x coordinate for the mouse location
y - the vertical y coordinate for the mouse location
clickCount - the number of mouse clicks associated with event
popupTrigger - a boolean, true if this event is a trigger for a popup menu
Methods:
int getButton()
Returns which, if any, of the mouse buttons has changed state.
int getClickCount()
Returns the number of mouse clicks associated with this event.
in getX()
t Returns the horizontal x position of the event relative to the
source component.
in getY()
t Returns the vertical y position of the event relative to the source
component.
MouseWheelEvent
An event which indicates that the mouse wheel was rotated in a
component.
A wheel mouse is a mouse which has a wheel in place of the middle
button. This wheel can be rotated towards or away from the user. Mouse
wheels are most often used for scrolling, though other uses are possible.
The constant:
WHEEL_BLOCK_SCROLL Constant representing scrolling by a "block"
(like scrolling with page-up, page-down keys)
WHEEL_UNIT_SCROLL Constant representing scrolling by "units"
(like scrolling with the arrow keys)
Methods
int getScrollAmount()
Returns the number of units that should be scrolled in response to this
event.
int getScrollType()
Returns the type of scrolling that should take place in response to this
event.
int getUnitsToScroll()
This is a convenience method to aid in the implementation of the
common-case MouseWheelListener - to scroll a ScrollPane or
10
JScrollPane by an amount which conforms to the platform settings.
int getWheelRotation()
Returns the number of "clicks" the mouse wheel was rotated.
TextEvent
TextEvent which indicates that an object's text changed. This event is
generated by an object (such as a TextComponent) when its text changes.
The event is passed to every TextListener object which registered to
receive such events using the component's addTextListener method. The
constant is:
TEXT_FIRST The first number in the range of ids used for text events.
TEXT_LAST The last number in the range of ids used for text events.
TEXT_VALUE_CHANGED This event id indicates that object's text
changed.
TextEvent(Object source, int id) Constructs a TextEvent object.
o source - the (TextComponent) object that originated the event
o id - an integer that identifies the event type
Methods
String paramString() Returns a parameter string identifying this text event.
WindowEvent
A event that indicates that a window has changed its status. This event is
generated by a Window object when it is opened, closed, activated,
deactivated, iconified, or deiconified, or when focus is transferred into or
out of the Window.
The event is passed to every WindowListener object which registered to
receive such events using the window's addWindowListener method. Each
such listener object gets this WindowEvent when the event occurs. The
constant is :
WINDOW_ACTIVATED The window-activated event type.
WINDOW_CLOSED The window closed event.
WINDOW_CLOSING The "window is closing" event.
WINDOW_DEACTIVATED The window-deactivated event type.
WINDOW_DEICONIFIED The window deiconified event type.
Constructor:
WindowEvent(Window source,int id)
Constructs a WindowEvent object.
WindowEvent(Window source,int id,int oldState,int newState)
Constructs a WindowEvent object with the specified previous and new
window states.
WindowEvent(Window source,int id, Window opposite)
Constructs a WindowEvent object with the specified opposite Window.
11
WindowEvent(Window source, int id, Window opposite, int oldState,
int newState)
Constructs a WindowEvent object.
Method:
int getNewState()
For WINDOW_STATE_CHANGED events returns the new
state of the window.
int getOldState()
For WINDOW_STATE_CHANGED events returns the
previous state of the window.
Windo getOppositeWindow()
w Returns the other Window involved in this focus or activation
change.
Windo getWindow()
w Returns the originator of the event.
String paramString()
Returns a parameter string identifying this event.
ContainerEvent
A ContianerEvent is generated when a component is added to or removed from a
container.
There are two types of container events. The ContainerEvent class defines int
constants that can identify them; COMPONENT_ADDED and
COMPONENT_REMOVED. They indicate that a component has been added to
or remove from the container.
Constructor: ContainerEvent(Component src, int type, Component comp)
Src: is reference to the container that generated this event.
Type: of the event is specified by type.
Comp: that has been added to or removed from the container is comp.
Method
Container getContainer( ) obtain a reference to the container that
generated this event by using.
Component getChild( ) returns to the component that was
added to or removed from the
container.
InputEvent
The abstract class InputEvent is a subclass of CompoentEvent and is the subclass
for component input events.
12
Its subclass are KeyEvent and MouseEvent. The InputEvent class defines that following 8 integer
constants that can be used to obtain information about any modification associated with this event:
ALT_MASK BUTTON2_MASK META_MASK ALT_GRAPH_MASK
13
Listener Interface
ActionListerner
This interface defines the actionPerformed() method that is invoked an action
event occurs. Its general form is shown here:
Void actionPerformed(ActionEvent ae)
AdjustmentListner Interface
This interface defines the adjustmentValueChanged( ) method that is invoked
when an adjustment event occurs. Its general form is shown here
ComponentListner Interface
this interface defines four method that are invoked when a component is resized,
moved, show or hidden. Their general forms are shown here:
void componentResized(ComponentEvent ce)
void componentMoved(ComponentEvent ce)
void componentShown(ComponentEvent ce)
void componentHidden(ComponentEvent ce)
ContainerListner Interface
This interface two methods. When a component is added to a container,
componentAdded( ) is invoked. When a component is removed from a container,
componentRemoved() is invoked. Their general forms are show here:
Void compoentAdded(ContainerEvent ce)
Void compoentRemoved(ContainerEvent ce)
FocusListner Interface
This interface defines 2 methoda. When a component obtains keyboard focus,
focusGained( ) is invoked. When a component loses keyboard focus,
focusLost( ) is called. Their general forms are shown here:
Void focusGained(FocusEvent fc)
Void focusLost(FocusEvent fc)
ItemListerner
This intrefece defines the itemStateChanged( ) method that is invoked when the
state of an item changes. Its general form is shown here:
Void itemStateChanged(ItemEvent ie)
KeyListerner
This interface define 3 method. The keyPress( ) and keyReleased( ) methods are
invoked when a key is pressed nad released, respectively. The keyTyped( )
method is invoked when a character has been entered.
14
For example, if a user pressed and releases the A key, three events are generated
in sequence: key pressed, type, and released. If a presses and releases the HOME
key, two key events are generated in sewuence:key pressed and released.
The general forms of these methods are shown here:
Void keyPressed(KeyEvent ke)
Void keyReleased(KeyEvent ke)
Void keyTyped(KeyEvent ke)
MouseListerner
This interface defines five method. If the mouse is pressed and released at the
same point, mouseClicked( ) is invoked. When the mouse enters a component
the mouseEntered( ) method is called. When it leaves, mouseExited( ) is called.
The mousePressed( ) and mouseReleased ( ) methods are invoked when the
mouse is pressed and released, respectively. The general forms of these methods
are shown here:
Void mouseClicked(MouseEvent me)
Void mouseEntered(MouseEvent me)
Void mouseExited(MouseEvent me)
Void mousePressed(MouseEvent me)
Void mouseReleased(MouseEvent me)
MouseMotionListerner
This interface defines two methods. The mouseDragged( ) method is called
multiple times as the mouse is dragged. The mouseMoved ( ) method is called
multiple times as the mouse is moved. Their general forms are shown here:
Void mouseDragged(MouseEvent me)
Void mouseMoved(MouseEvent me)
MouseWheelListener Interface
This interface defines the mouseWheelMoved( ) method that is invoked when
the mouse wheel is moved. Its general forms are shown here:
Void mouseWheelMoved(MouseWheelEvent mw)
TextListerner
This interface define the textChanged( ) method that is invoked when a change
occure in a text area or text field. Its general form is shown here.
Void textChanged(TextEvent te)
WindowFocusListener Interface
This interface define 2 methods:windowGainedFocus( ) and
windowLostFocus( ). These are called when a window gains or loses input
focus. Their general forms are shown here:
15
Void windowGainedFocus(WindowEvent we)
Void WindowLostFocus(WindowEvent we)
WindowListerner
This intereface defines 7 methods. The windowActivated( ) and
windowDeactivated( ) methods are invoked when a window is activated or
deactivated, respectively.
If a widow is iconified, the windowIconified( ) method called. When a window
is deiconified, the windowDeiconified( ) method is called.
When a window is opened or closed, the windowOpended( ) or windowClosed( )
metod are called.
The window windowClosing( ) method is called when a window is being closed.
The general forms of these methods are
Void windowActivated(WindowEvent we)
Void windowDeactivated(WindowEvent we)
Void windowClose(WindowEvent we)
Void windowCloseing(WindowEvent we)
Void windowDeiconified(WindowEvent we)
Void windowIconified(WindowEvent we)
Void windowOpened(WindowEvent we)
case KeyEvent.VK_F2:
msg += "<F2>";
break;
case KeyEvent.VK_F3:
msg += "<F3>";
break;
case KeyEvent.VK_PAGE_DOWN:
msg += "<Page Down>";
break;
case KeyEvent.VK_PAGE_UP:
msg += "<Page Up>";
break;
case KeyEvent.VK_LEFT:
msg += "<Left Arrow>";
break;
case KeyEvent.VK_RIGHT:
msg += "<Right Arrow>";
break;
}
repaint();
18
}
public void keyReleased(KeyEvent ke)
{
showStatus("Key Up");
}
public void keyTyped(KeyEvent ke)
{
msg += ke.getKeyChar();
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,x,y);
}
}
19
Adapter Classes
In last example we have seen that the MouseListener interface declares
five methods. These are called when the mouse is clicked, pressed or released.
Mouse events also occur when the mouse enters or exits a component.
The main problem here is it has to implement all the five methods declared
by that interface even though we don’t require them. This is very much
inconvenient.
Adapter classes make it easy to deal with this situation. An adapter class
provides empty implementation of all methods in a particular listener interface.
It can be useful if you want to override only some of the methods defined by the
interface.
Various adapter classes for various listener interfaces are as follows :
Adapter Class Listener Class
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
FocusAdapter FocusListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
WindowAdapter WindowsListener
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*<applet code="MouseAdapterDemo" width=200 height=120>
</applet>*/
public class MouseAdapterDemo extends Applet
{
public void init()
{
setBackground(Color.green);
addMouseListener(new MyMouseAdapter(this));
}
}
class MyMouseAdapter extends MouseAdapter
{
20
MouseAdapterDemo mad;
public MyMouseAdapter(MouseAdapterDemo mad)
{
this.mad = mad;
}
public void mousePressed(MouseEvent me)
{
mad.setBackground(Color.red);
mad.repaint();
}
public void mouseReleased(MouseEvent me)
{
mad.setBackground(Color.green);
mad.repaint();
}
}
Inner Classes
An inner class is defined within the scope of an expression or
another class. Therefore it has access to the variables and methods in that scope.
We have already learned about the inner classes in previous unit no. 2.
Here we will see how we can use inner classes with adapter for mouse events.
Here we will define the adapter class inside the main class.
When we compile the above file It will generate two .class files. These are
MouseInnerDemo.class and MouseInnerDemo$MyMouseAdapter.class
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code="MouseInnerDemo" width=100 height=100></applet>
*/
public class MouseInnerDemo extends Applet
{
public void init()
{
setBackground(Color.green);
addMouseListener(new MyMouseAdapter());
}
class MyMouseAdapter extends MouseAdapter
{
public void mousePressed(MouseEvent me)
{
setBackground(Color.red);
repaint();
21
}
public void mouseReleased(MouseEvent me)
{
setBackground(Color.green);
repaint();
}
}
}
An anonymous inner class is an inner class that does not have a name.
Anonymous inner class will be declared generally inside the method by
using new keyword with the class.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code="MouseAnonymousDemo" width=100 height=100></applet>
*/
public class MouseAnonymousDemo extends Applet
{
public void init()
{
setBackground(Color.green);
addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent me)
{
setBackground(Color.red);
repaint();
}
public void mouseReleased(MouseEvent me)
{
setBackground(Color.green);
repaint();
}
});
}
}
22