Event Handling
Event Handling
Event Handling is the mechanism that controls the event and decides
what should happen if an event occurs. This mechanism have the code
which is known as event handler that is executed when an event occurs.
Java Uses the Delegation Event Model to handle the events.
Event handling isfundamental to Java programming because it is integral to
the creation of applets andother types of GUI-based programs. Applets are
event-drivenprograms that use a graphical user interface to interact with
the user.
Events are supported by a number of packages, including java.awt,
andjava.awt.event.
Most events to which your program will respond are generated when the
user interactswith a GUI-based program. There are several types of events,
including those generated by the mouse, thekeyboard, and various GUI
controls, such as a push button, scroll bar, or check box.
The Delegation Event Model
o Events
o Sources
o Listeners
Events:
An event is an object that describes a state change in a source.
It canbe generated as a consequence of a person interacting with the
elements in a graphical userinterface. Some of the activities that cause
events to be generated are pressing a button, enteringa character via the
keyboard, selecting an item in a list, and clicking the 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.
Event Sources
A source generates an event and sends it to one or more listeners.
Asource is an object that generates an event.
This occurs when the internal state of that objectchanges in some way.
Sources may generate more than one type of event.Asource must register
listeners in order for the listeners to receive notifications abouta specific
type of event. Each type of event has its own registration method. Here is
thegeneral form:
public void addTypeListener(TypeListenerel)
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 methodthat registers a mouse motion listener is called
addMouseMotionListener( ). When an eventoccurs, all registered listeners
are notified and receive a copy of the event object.
A source must also provide a method that allows a listener to unregister an
interestin a specific type of event.
The general form of such a method is this:
public void removeTypeListener(TypeListenerel)
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
generatesevents.
For example, the Component class provides methods to add and remove
keyboardand 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 aboutspecific types of events. Second, it must implement
methods to receive and process thesenotifications.
The methods that receive and process events are defined in a set of
interfaces found injava.awt.event.
For example, the MouseMotionListenerinterface defines two methods
toreceive notifications when the mouse is dragged or moved.
Event Classes
The classes that represent events are at the core of Java’s event handling
mechanism. The most widely used events are those defined by the AWT
and those defined by Swing.
COMPLETE DESCRIPTION OF delegation event model
Sources of Events
Event Classes
The getComponent( ) method returns the component that generated the event. It
isshown here:Component getComponent( )
The ContainerEvent Class
AContainerEventis generated when a component is added to or removed from a
container.
There are two types of container events. The ContainerEventclass defines
intconstants thatcan be used to identify them:
COMPONENT_ADDED and COMPONENT_REMOVED.
They indicate that a component has been added to or removed from the
container.
ContainerEventis a subclass of ComponentEventand has this constructor:
ContainerEvent(Component src, inttype, Component comp)
Here, srcis a reference to the container that generated this event. The type of the
event is specifiedby type, and the component that has been added to or removed
from the container is comp.
You can obtain a reference to the container that generated this event by using the
getContainer( ) method, shown here:
Container getContainer( )
The getChild( ) method returns a reference to the component that was added to
or removedfrom the container. Its general form is shown here:
Component getChild( )
AKeyEventis generated when keyboard input occurs. There are three types of key
events,which are identified by these integer constants:
KEY_PRESSED, KEY_RELEASED, andKEY_TYPED.
The first two events are generated when any key is pressed or released. Thelast
event occurs only when a character is generated. Remember, not all keypresses
resultin characters. For example, pressing SHIFT does not generate a character.
There are many other integer constants that are defined by KeyEvent. For
example, VK_0through VK_9 and VK_A through VK_Z define the ASCII equivalents
of the numbers andletters.
There are eight types of mouse events. The MouseEventclass defines the
following integerconstants that can be used to identify them:
Instances of this class describe text events. These are generated by text fields and
text areaswhen characters are entered by a user or program.
TextEventdefines the integer constant
TEXT_VALUE_CHANGED.
The delegation event model has two parts: sources and listeners. Listeners
arecreated by implementing one or more of the interfaces defined by the
java.awt.eventpackage.When an event occurs, the event source invokes the
appropriate method defined by thelistener and provides an event object as its
argument. The following table lists commonly used listenerinterfaces and
provides a brief description of the methods that they define.
The ActionListener Interface
This interface defines four methods that are invoked when a component is
resized, moved,shown, or hidden. Their general forms are shown here:
void componentResized(ComponentEventce)
void componentMoved(ComponentEventce)
void componentShown(ComponentEventce)
void componentHidden(ComponentEventce)
void componentAdded(ContainerEventce)
void componentRemoved(ContainerEventce)
The FocusListener Interface
This interface defines two methods. When a component obtains keyboard focus,
focusGained( )is invoked. When a component loses keyboard focus, focusLost( ) is
called. Their generalforms are shown here:
void focusGained(FocusEventfe)
void focusLost(FocusEventfe)
This interface defines the itemStateChanged( ) method that is invoked when the
state of anitem changes. Its general form is shown here:
void itemStateChanged(ItemEventie)
void keyPressed(KeyEventke)
void keyReleased(KeyEventke)
void keyTyped(KeyEventke)
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( ) andmouseReleased( ) methods are invoked when the mouse is
pressed and released, respectively.
The general forms of these methods are shown here:
void mouseClicked(MouseEventme)
void mouseEntered(MouseEventme)
void mouseExited(MouseEventme)
void mousePressed(MouseEventme)
void mouseReleased(MouseEventme)
void mouseDragged(MouseEventme)
void mouseMoved(MouseEventme)
void mouseWheelMoved(MouseWheelEventmwe)
This interface defines the textChanged( ) method that is invoked when a change
occursin a text area or text field. Its general form is shown here:
void textChanged(TextEventte)
There are eight types of mouse events. The MouseEvent class defines the
following integer constants that can be used to identify them:
To handle mouse events, you must implement the MouseListener and the
MouseMotionListener interfaces. The following applet demonstrates the process.
It displays the current coordinates of the mouse in the applet’s status window.
Each time a button is pressed, the word “Down” is displayed at the location of the
mouse pointer. Each time the button is released, the word “Up” is shown. If a
button is clicked, the message “Mouse clicked” is displayed in the upper left
corner of the applet display area.
As the mouse enters or exits the applet window, a message is displayed in the
upper-left corner of the applet display area. When dragging the mouse, a * is
shown, which tracks with the mouse pointer as it is dragged. Notice that the two
variables, mouseX and mouseY, store the location of the mouse when a mouse
pressed, released, or dragged event occurs. These coordinates are then used by
paint( ) to display output at the point of these occurrences.
// show status
showStatus("Moving mouse at " + me.getX() + ", " + me.getY());
}
// Display msg in applet window at current X,Y location.
public void paint(Graphics g)
{
g.drawString(msg, mouseX, mouseY);
}
}
Output :
The MouseEvents class extends Applet and implements both the MouseListener
and MouseMotionListener interfaces. These two interfaces contain methods that
receive and process the various types of mouse events. Notice that the applet is
both the source and the listener for these events. This works because
Component, which supplies the addMouseListener() and
addMouseMotionListener( ) methods, is a super class of Applet. Being both the
source and the listener for events is a common situation for applets. Inside init( ),
the applet registers itself as a listener for mouse events. This is done by using
addMouseListener( ) and addMouseMotionListener( ), which, as mentioned, are
members of Component.
They are shown here:
void addMouseListener(MouseListener ml)
voidaddMouseMotionListener(MouseMotionListener mml)
Handling Keyboard Events
A KeyEvent is generated when keyboard input occurs. There are three types of
key events, which are identified by these integer constants:
KEY_PRESSED, KEY_RELEASED, and KEY_TYPED.
To handle keyboard events, you use the same general architecture as that shown
in the mouse event example in the preceding section. The difference, of course, is
that you will be implementing the KeyListener interface.
Before looking at an example, it is useful to review how key events are generated.
When a key is pressed, a KEY_PRESSED event is generated. This results in a call to
the keyPressed( )event handler. When the key is released, a EY_RELEASED event
is generated and the keyReleased( ) handler is executed. If a character is
generated by the keystroke, then a KEY_TYPED event is sent and the keyTyped( )
handler is invoked. Thus, each time the user presses a key, at least two and often
three events are generated. If all you care about are actual characters, then you
can ignore the information passed by the key press and release events.
However, if your program needs to handle special keys, such as the arrow or
function keys, then it must watch for them through the keyPressed( ) handler.
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 you want to receive and process only some of the events
that are handled by a particular event listener interface.
You 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 you are interested.
For example, the MouseMotionAdapter class has two methods,
mouseDragged( )and mouseMoved( ), which are the methods defined by the
MouseMotionListener interface.
If you were interested in only mouse drag events, then you could simply extend
MouseMotionAdapter and override mouseDragged( ). The empty
implementation of mouseMoved( ) would handle the mouse motion events for
you.
The above table lists the commonly used adapter classes in java.awt.event and
notes the interface that each implements.
The following example demonstrates an adapter. It displays a message in the
status bar of an applet viewer or browser when the mouse is clicked or dragged.
However, all other mouse events are silently ignored. The program has three
classes. AdapterDemo extends Applet. Its init( ) method creates an instance of
MyMouseAdapter and registers that object to receive notifications of mouse
events. It also creates an instance of MyMouseMotionAdapter and registers that
object to receive notifications of mouse motion events. Both of the constructors
take a reference to the applet as an argument.
MyMouseAdapter extends MouseAdapter and overrides the mouseClicked( )
method. The other mouse events are silently ignored by code inherited from the
MouseAdapter class. MyMouseMotionAdapter extends MouseMotionAdapter
and overrides the mouseDragged( ) method. The other mouse motion event is
silently ignored by code inherited from the MouseMotionAdapter class.
Note that both of the event listener classes save a reference to the applet. This
information is provided as an argument to their constructors and is used later to
invoke the showStatus( )
method.
// Demonstrate an adapter.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="AdapterDemo" width=300 height=100>
</applet>
*/
public class AdapterDemo extends Applet
{
public void init() {
addMouseListener(new MyMouseAdapter(this));
addMouseMotionListener(new MyMouseMotionAdapter(this));
}
}
class MyMouseAdapter extends MouseAdapter
{
AdapterDemoadapterDemo;
public MyMouseAdapter(AdapterDemoadapterDemo)
{
this.adapterDemo = adapterDemo;
}
// Handle mouse clicked.
public void mouseClicked(MouseEvent me)
{
adapterDemo.showStatus("Mouse clicked");
}
}
class MyMouseMotionAdapter extends MouseMotionAdapter
{
AdapterDemoadapterDemo;
public MyMouseMotionAdapter(AdapterDemoadapterDemo)
{
this.adapterDemo = adapterDemo;
}
// Handle mouse dragged.
public void mouseDragged(MouseEvent me)
{
adapterDemo.showStatus("Mouse dragged");
}
}
As you can see by looking at the program, not having to implement all of the
methodsdefined by the MouseMotionListenerand MouseListenerinterfaces saves
you a considerableamount of effort and prevents your code from becoming
cluttered with empty methods. Asan exercise, you might want to try rewriting one
of the keyboard input examples shown
earlier so that it uses a KeyAdapter.
Output :