Event handling
Event handling is fundamental to Java
programming because it is integral to the creation of applets and other types of
GUI-based programs as any program that uses a graphical user interface, such as
a Java application written for Windows, is event driven.
The Delegation Event Model
The modern approach to handling events is
based on the delegation event model, which defines standard and consistent
mechanisms to generate and process events. 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 an event is
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.
In the delegation event model, listeners
must register with a source in order to receive an event notification. This
provides an important benefit: notifications are sent only to listeners that
want to receive them.
Events
In the delegation model, an event is an
object that describes a state change in a source. 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.
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 software or hardware failure occurs, or an
operation is completed.
Event Sources
Asource is an object that generates an
event. Asource 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. Here is the general form:
public void
addTypeListener(TypeListener el)
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(
).
When an event occurs, all registered
listeners are notified and receive a copy of the event object. This is known as
multicasting the event. In all cases,
notifications are sent only to listeners that register to receive them. Some
sources may allow only one listener to register. When such an event occurs, the
registered listener is notified. This is known as unicasting the event.
A source must also provide a method that
allows a listener to unregister an interest in a specific type of event. The
general form of such a method is this:
public void
removeTypeListener(TypeListener el)
Here, Type is the name of the event, and el
is a reference to the event listener. For example, to remove a keyboard
listener, you would call removeKeyListener(
).
The methods that add or remove listeners
are provided by the source that generates events. For example, the Component
class provides methods to add and remove keyboard and mouse event listeners.
Event Listeners
Alistener 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 found in java.awt.event. For example, the
MouseMotionListener interface defines two methods to receive notifications when
the mouse is dragged or moved.
Using the Delegation Event Model
Using the Delegation Event Model involves
just two steps:
·
Implement the appropriate
interface in the listener so that it will receive the type of event desired.
·
Implement code to register and
unregister (if necessary) the listener as a recipient for the event
notifications.
An Example
/* <applet code = "AppletMouse"
height = "150" width = "300">
</applet> */
import java.awt.*;
import
java.awt.event.*;
import java.applet.*;
public class
AppletMouse extends Applet implements MouseListener{
public void init(){
setBackground(Color.white);
setForeground(Color.red);
addMouseListener(this);
}
public void paint(Graphics g){
g.drawString("Mouse Event
Test",100,75);
}
public void mousePressed(MouseEvent me){
showStatus("Mouse
Pressed");
}
public
void mouseReleased(MouseEvent me){
showStatus("Mouse
Released");
}
public void mouseEntered(MouseEvent me){
showStatus("Mouse
Entered");
}
public void mouseDragged(MouseEvent me){
showStatus("Mouse
Dragged");
}
public void mouseExited(MouseEvent me){
showStatus("Mouse
Exited");
}
public void mouseMoved(MouseEvent me){
showStatus("Mouse
Moved");
}
public void mouseClicked(MouseEvent me){
showStatus("Mouse
Clicked");
}
}
Output
The above program demonstrates a simple
event handling example. As the code shows, the class AppletMouse implements the listener interface MouseListener. Here the applet is the source of the events, in
order to register the listener with source we have used the method addMouseListener() method. As shown we
have passed this (an object of AppletMouse) as the argument to the
method. It means that the methods of the interface are implemented in the
current class (i.e. AppletMouse).
Below we see that all the methods of MouseListener
interface are defined. The AWT Runtime system calls the appropriate methods
based on the event that occurs from mouse. In each of such method (for example: void mouseClicked(MouseEvent me))
receives an object of the MouseEvent class
as argument. This can be used to invoke the methods of MouseEvent class. The methods of various event classes and listener
interfaces are given below.
Event Classes
At the root of the Java event class
hierarchy is EventObject, which is in
java.util. It is the superclass for
all events. 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. Its getID( ) method can be used to determine the
type of the event. The signature of this method is:
int getID( )
The integer returned by this method can be
compared with the integer constants defined in event classes to identify the
event occurred.
The package java.awt.event defines many types of events that are generated by
various user interface elements.
Given below lists the major event classes
with a small description of each:
Event Class
|
Description
|
ActionEvent
|
Generated when a button is pressed, a list
item is double-clicked, or a menu item is selected.
|
AdjustmentEvent
|
Generated when a scroll bar is manipulated.
|
ComponentEvent
|
Generated when a component is hidden,
moved, resized, or becomes visible.
|
ContainerEvent
|
Generated when a component is added to or
removed from a container.
|
FocusEvent
|
Generated when a component gains or loses
keyboard focus.
|
InputEvent
|
Abstract superclass for all component input
event classes.
|
ItemEvent
|
Generated when a check box or list item is
clicked; also occurs when a choice selection is made or a checkable menu item
is selected or deselected.
|
KeyEvent
|
Generated when input is received from the
keyboard.
|
MouseEvent
|
Generated when the mouse is dragged, moved,
clicked, pressed, or released.
Also generated when the mouse enters or
exits a component.
|
MouseWheelEvent
|
Generated when the mouse wheel is moved.
|
TextEvent
|
Generated when the value of a text area or
text field is changed.
|
WindowEvent
|
Generated when a window is activated,
closed, deactivated, deiconified, iconified, opened, or quit.
|
The ActionEvent Class
An ActionEvent is generated when a button
is pressed, a list item is double-clicked, or a menu item is selected.
You can obtain the command name for the
invoking ActionEvent object by using the getActionCommand( ) method, shown
here:
String getActionCommand( )
For example, when a button is pressed, an
action event is generated that has a command name equal to the label on that
button.
The getModifiers( ) method returns a value
that indicates which modifier keys (ALT, CTRL, META, and/or SHIFT) were pressed
when the event was generated. Its form is shown here:
int getModifiers( )
The method getWhen( ) returns the time at
which the event took place. This is called the event’s timestamp. The getWhen(
) method is shown here:
long getWhen( )
The AdjustmentEvent Class
An AdjustmentEvent is generated by a scroll
bar. There are five types 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 increase its value.
TRACK The slider was dragged.
UNIT_DECREMENT The button at the end of the
scroll bar was clicked to decrease its value.
UNIT_INCREMENT The button at the end of the
scroll bar was clicked to increase its value.
The getAdjustable( ) method returns the
object that generated the event. Its form is
shown here:
Adjustable getAdjustable( )
The type of the adjustment event may be
obtained by the getAdjustmentType( ) method. It
returns one of the constants defined by
AdjustmentEvent. The general form is shown here:
int getAdjustmentType( )
The amount of the adjustment can be obtained
from the getValue( ) method, shown here:
int getValue( )
For example, when a scroll bar is
manipulated, this method returns the value represented
by that change.
The MouseEvent Class
There are eight types of mouse events. The
MouseEvent class defines the following integer constants that can be used to
identify them:
MOUSE_CLICKED The user clicked the mouse.
MOUSE_DRAGGED The user dragged the mouse.
MOUSE_ENTERED The mouse entered a
component.
MOUSE_EXITED The mouse exited from a
component.
MOUSE_MOVED The mouse moved.
MOUSE_PRESSED The mouse was pressed.
MOUSE_RELEASED The mouse was released.
MOUSE_WHEEL The mouse wheel was moved.
MouseEvent is a subclass of InputEvent.
Two commonly used methods in this class are
getX( ) and getY( ). These return the X and Y coordinates of the mouse within
the component when the event occurred. Their forms are:
int getX( )
int getY( )
The getClickCount( ) method obtains the
number of mouse clicks for this event.Its signature is shown here:
int getClickCount( )
Listener Interfaces
Following are the commonly used Listener
Interfaces. The methods that are defined in each of these listeners are also
listed. Before we go into the details, the following table summarizes the
listeners defined in java.awt.event
package:
Interface
|
Description
|
ActionListener
|
Defines one method to receive
action events.
|
AdjustmentListener
|
Defines one method to receive adjustment
events.
|
ComponentListener
|
Defines four methods to
recognize when a component is hidden, moved, resized, or shown.
|
ContainerListener
|
Defines two methods to recognize when a
component is added to or removed from a container.
|
FocusListener
|
Defines two methods to recognize
when a component gains or loses keyboard focus.
|
ItemListener
|
Defines one method to recognize when the
state of an item changes.
|
KeyListener
|
Defines three methods to
recognize when a key is pressed, released, or typed.
|
MouseListener
|
Defines five methods to recognize when the
mouse is clicked, enters a component, exits a component, is pressed, or is
released.
|
MouseMotionListener
|
Defines two methods to recognize
when the mouse is dragged or moved.
|
MouseWheelListener
|
Defines one method to recognize when the
mouse wheel is moved.
|
TextListener
|
Defines one method to recognize
when a text value changes.
|
WindowFocusListener
|
Defines two methods to recognize when a
window gains or loses input focus.
|
WindowListener
|
Defines seven methods to
recognize when a window is activated, closed, deactivated, deiconified,
iconified, opened, or quit.
|
Let us start with the MouseListener which we
have already seen in the example above.
The MouseListener Interface
This interface defines five methods. 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:
void mouseClicked(MouseEvent me)
void mouseEntered(MouseEvent me)
void mouseExited(MouseEvent me)
void mousePressed(MouseEvent me)
void mouseReleased(MouseEvent me)
The MouseMotionListener Interface
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:
void mouseDragged(MouseEvent me)
void mouseMoved(MouseEvent me)
The ActionListener Interface
This interface defines the actionPerformed(
) method that is invoked when an action event occurs. Its general form is shown
here:
void actionPerformed(ActionEvent ae)
The KeyListener Interface
This interface defines three methods. The
keyPressed( ) and keyReleased( ) methods are invoked when a key is pressed and
released, respectively. The keyTyped( ) method is invoked when a character has
been entered.
For example, if a user presses and releases
the A key, three events are generated in sequence: key pressed, typed, and
released. If a user presses and releases the HOME key, two key events are
generated in sequence: 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)
The WindowListener Interface
This interface defines seven methods. The
windowActivated( ) and windowDeactivated( ) methods are invoked when a window
is activated or deactivated, respectively. If a window is iconified, the
windowIconified( ) method is called. When a window is deiconified, the
windowDeiconified( ) method is called. When a window is opened or closed, the
windowOpened( ) or windowClosed( ) methods are called, respectively. The
windowClosing( ) method is called when a window is being closed. The general
forms of these methods are:
void windowActivated(WindowEvent we)
void windowClosed(WindowEvent we)
void windowClosing(WindowEvent we)
void windowDeactivated(WindowEvent we)
void windowDeiconified(WindowEvent we)
void windowIconified(WindowEvent we)
void windowOpened(WindowEvent we)

No comments:
Post a Comment