0% found this document useful (0 votes)
2 views14 pages

Event-Handling

k scheme

Uploaded by

surajkhavare013
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views14 pages

Event-Handling

k scheme

Uploaded by

surajkhavare013
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

Chapter 3:Event Handling

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. This is a more efficient way to handle events
than the design used
by the old Java 1.0 approach. Previously, an event was propagated up the
containment hierarchy until it was handled by a component. This required
components to receive events that they did not process, and it wasted
valuable time. The delegation event model eliminates this overhead.

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. Many other
user operations could also be cited as examples.
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,
a software or hardware failure occurs, or an operation is completed.
You are free to define events that are appropriate for your application.

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. 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 Some sources may allow only one listener to register. The
general form of such a method is this:
public void addTypeListener(TypeListener el)
throws java.util.TooManyListenersException
Here, Type is the name of the event, and el is a reference to the event
listener. 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.example,the method that registers a keyboard
event listener is called addKeyListener( ). The method that registers a
mouse motion listener is called addMouseMotionListener( ). 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.

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 found in
java.awt.event. 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.

Adapater 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
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.

lists the commonly used adapter classes in java.awt.event and notes the
interface that each implements:-
Adapater class Listener interface
ComponentAdapter CompnentListener
ContainerAdapter ContainerListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
WindowAdapter WindowListener
FocusAdapter FocusListener

Inner Classes:-
The most important type of nested class is the inner class. An inner class
is a non-static
nested class. It has access to all of the variables and methods of its outer
class and may refer
to them directly in the same way that other non-static members of the
outer class do.
The following program illustrates how to define and use an inner class.
The class named
Outer has one instance variable named outer_x, one instance method
named test( ), and
defines one inner class called Inner.
// Demonstrate an inner class.
class Outer {
int outer_x = 100;
void test() {
Inner inner = new Inner();
inner.display();
}
// this is an inner class
class Inner {
void display() {
System.out.println("display: outer_x = " + outer_x);
}
}
}
class InnerClassDemo {
public static void main(String args[]) {
Outer outer = new Outer();
outer.test();
}
}
Output from this application is shown here:
display: outer_x = 100
Simple,Inner class is class that is defined within another class.

Anonymous Inner classes:-


An anonymous inner class is one that is not assigned a name. This section
illustrates how an
anonymous inner class can facilitate the writing of event handlers.
Consider the applet shown
in the following listing. As before, its goal is to display the string “Mouse
Pressed” in the
status bar of the applet viewer or browser when the mouse is pressed.
// Anonymous inner class demo.
import java.applet.*;
import java.awt.event.*;
/*
<applet code="AnonymousInnerClassDemo" width=200 height=100>
</applet>
*/
public class AnonymousInnerClassDemo extends Applet {
public void init() {
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
showStatus("Mouse Pressed");
}
});
}
}
There is one top-level class in this program: AnonymousInnerClassDemo.
The init( )
method calls the addMouseListener( ) method. Its argument is an
expression that defines
and instantiates an anonymous inner class. Let’s analyze this expression
carefully.
The syntax new MouseAdapter( ) { ... } indicates to the compiler that the
code between the
braces defines an anonymous inner class. Furthermore, that class extends
MouseAdapter. This
new class is not named, but it is automatically instantiated when this
expression is executed.
Because this anonymous inner class is defined within the scope of
AnonymousInnerClassDemo, it has access to all of the variables and
methods within
the scope of that class. Therefore, it can call the showStatus( ) method
directly.
As just illustrated, both named and anonymous inner classes solve some
annoying
problems in a simple yet effective way.

Event Classes:-
The classes that represent events are at the core of Java’s event handling
mechanism. Thus, a
discussion of event handling must begin with the event classes. The most
widely used events are those defined by the AWT and those defined by
Swing.

At the root of the Java event class hierarchy is EventObject, which is in


java.util. It is the
superclass for all events. Its one constructor is shown here:
EventObject(Object src)
Here, src is the object that generates this event.

EventObject contains two methods: getSource( ) and toString( ).


The getSource( ) method returns the source of the event.
Its general form is shown here: Object getSource( )
As expected, toString( ) returns the string equivalent of the event.

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 shown
here:
int getID( )
The package java.awt.event defines many types of events that are
generated by various
user interface elements.

ActionEvent Class:-
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 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 three constructors:
ActionEvent(Object src, int type, String cmd)
ActionEvent(Object src, int type, String cmd, int
modifiers)
ActionEvent(Object src, int type, String cmd, long when,
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. The when
parameter specifies when the event occurred.

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(
)

ItemEvent Class:-
An ItemEvent is generated when a check box or a list item is clicked or
when a checkable menu item is selected or deselected. (Check boxes and
list boxes are described later in this book.)
There are two types of item events, which are identified by the following
integer constants:
1.DESELECTED:- The user deselected an item.
2.SELECTED:- The user selected an item.
In addition, ItemEvent defines one integer constant,
ITEM_STATE_CHANGED, that
signifies a change of state.

ItemEvent has this constructor: ItemEvent(ItemSelectable src, int type,


Object entry, int state)
Here, src is a reference to the component that generated this event. For
example, this might
be a list or choice element. The type of the event is specified by type. The
specific item that
generated the item event is passed in entry. The current state of that item
is in state.

The getItem( ) method can be used to obtain a reference to the item that
generated an
event. Its signature is shown here: Object getItem( )
object that generated an event. Its general form is shown
here:ItemSelectable getItemSelectable( )
Lists and choices are examples of user interface elements that implement
the ItemSelectable
interface. The getStateChange( ) method returns the state change (that is,
SELECTED or
DESELECTED) for the event. It is shown here: int getStateChange( )
KeyEvent Class:-
AKeyEvent 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. The first two events are
generated when any key is pressed or released. The last event occurs only
when a character is generated. Remember, not all keypresses result in
characters. For example, pressing SHIFT does not generate a character.
There are many other integer constants that are defined by KeyEvent. For
example, VK_0
through VK_9 and VK_A through VK_Z define the ASCII equivalents of the
numbers and
letters.
Following table shows constants in KeyEvent class:-
KEY_PRESSED KEY_RELEASED
KEY_TYPED VK_0 TO VK_9
VK_A TO VK_Z VK_CONTROL
VK_SHIFT VK_UP
VK_DOWN VK_PAGE_UP
VK_PAGE_DOWN VK_CANCLE
VK_UNDEFINED CHAR_UNDEFINED
VK_LEFT VK_RIGHT
VK_ENTER VK_ESCAPE

The VK constants specify virtual key codes and are independent of any
modifiers, such as
control, shift, or alt. KeyEvent is a subclass of InputEvent. Here is one of
its constructors:
KeyEvent(Component src, int type, long when, int modifiers, int
code, char ch)
Here, src is a reference to the component that generated the event. The
type of the event is
specified by type. The system time at which the key was pressed is
passed in when. The modifiers argument indicates which modifiers were
pressed when this key event occurred. The virtual key code, such as
VK_UP, VK_A, and so forth, is passed in code. The character equivalent (if
one exists) is passed in ch. If no valid character exists, then ch contains
CHAR_UNDEFINED. For KEY_TYPED events, code will contain
VK_UNDEFINED.

The KeyEvent class defines several methods, but the most commonly
used ones are
getKeyChar( ), which returns the character that was entered, and
getKeyCode( ), which
returns the key code.
Their general forms are shown here:
char getKeyChar( )
int getKeyCode( )
If no valid character is available, then getKeyChar( ) returns
CHAR_UNDEFINED. When
a KEY_TYPED event occurs, getKeyCode( ) returns VK_UNDEFINED.
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_PRESSED The user pressed the mouse.
MOUSE_RELEASED The user released the mouse.
MOUSE_ENTERED The mouse entered in the
component.
MOUSE_DRAGGED The use dragged the mouse.
MOUSE_WHEEL The mouse wheel was moved.
MOUSE_MOVED The mouse
MOUSE_EXITED The mouse exited from the
component.

MouseEvent is a subclass of InputEvent. Here is one of its constructors:


MouseEvent(Component src, int type, long when, int modifiers, int x, int y,
int clicks, Boolean triggersPopup)
Here, src is a reference to the component that generated the event. The
type of the event is
specified by type. The system time at which the mouse event occurred is
passed in when. The
modifiers argument indicates which modifiers were pressed when a
mouse event occurred.
The coordinates of the mouse are passed in x and y. The click count is
passed in clicks. The
triggersPopup flag indicates if this event causes a pop-up menu to appear
on this platform.

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 shown here:
int getX( )
int getY( )
Alternatively, you can use the getPoint( ) method to obtain the
coordinates of the mouse. It is shown here:
Point getPoint( )
It returns a Point object that contains the X,Y coordinates in its
integer members: x and y.
The translatePoint( ) method changes the location of the event. Its form is
shown here:
void translatePoint(int x, int y)
Here, the arguments x and y are added to the coordinates of the event.
The getClickCount( ) method obtains the number of mouse clicks for this
event. Its signature is shown here:
int getClickCount( )
The isPopupTrigger( ) method tests if this event causes a pop-up menu to
appear on this
platform. Its form is shown here:
boolean isPopupTrigger( )
Also available is the getButton( ) method, shown here:
int getButton( )
It returns a value that represents the button that caused the event. The
return value will be
one of these constants defined by MouseEvent:
NOBUTTON BUTTON1 BUTTON2 BUTTON3
The NOBUTTON value indicates that no button was pressed or released.
Java SE 6 added three methods to MouseEvent that obtain the coordinates
of the mouse relative to the screen rather than the component. They are
shown here:
Point getLocationOnScreen( )
int getXOnScreen( )
int getYOnScreen( )
The getLocationOnScreen( ) method returns a Point object that contains
both the X andY coordinate. The other two methods return the indicated
coordinate.
TextEvent Class:-
Instances of this class describe text events. These are generated by text
fields and text areas
when characters are entered by a user or program.
TextEvent defines the integer constant TEXT_VALUE_CHANGED.
The one constructor for this class is shown here:
TextEvent(Object src, int type)
Here, src is a reference to the object that generated this event. The type
of the event is
specified by type.
The TextEvent object does not include the characters currently in the text
component that
generated the event. Instead, your program must use other methods
associated with the text
component to retrieve that information. This operation differs from other
event objects
discussed in this section. For this reason, no methods are discussed here
for the TextEvent
class.

WindowEvent Class:-
There are ten types of window events. TheWindowEvent class defines
integer constants that
can be used to identify them. The constants and their meanings are
shown here:
WINDOW_CLOSED The window has been closed.
WINDOW_CLOSING The user requested that the
window be closed.
WINDOW_ACTIVATED The window was activated.
WINDOW_DEACTIVATED The window was deactivated.
WINDOW_ICONIFIED The window was iconified.
WINDOW_DEICONIFIED The window was deiconified.
WINDOW_OPEND The window was opened.
WINDOW_GAINED_FOCUS The window gained input focus.
WINDOW_LOST_FOCUS The window lost input focus.
WINDOW_STATE_CHANGED The state of the window changed.
WindowEvent is a subclass of ComponentEvent. It defines several constructors.
The first is:
WindowEvent(Window src, int type)
Here, src is a reference to the object that generated this event. The type of the event is type.
The next three constructors offer more detailed control:
WindowEvent(Window src, int type, Window
other)
WindowEvent(Window src, int type, int
fromState, int toState)
WindowEvent(Window src, int type, Window
other, int fromState, int toState)
Here, other specifies the opposite window when a focus or activation event occurs. The
fromState specifies the prior state of the window, and toState specifies the new state that the
window will have when a window state change occurs.
Acommonly used method in this class is getWindow( ). It returns the Window object that
generated the event. Its general form is shown here:
Window getWindow( )
WindowEvent also defines methods that return the opposite window (when a focus or
activation event has occurred), the previous window state, and the current window state.
These methods are shown here:
Window getOppositeWindow( )
int getOldState( )
int getNewState( )
Interfaces:-
delegation event model has two parts: sources and listeners.
Listeners are created by implementing one or more of the interfaces
defined by the java.awt.event package.

1.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)

2.AdjustmentListener Interface:-
This interface defines the adjustmentValueChanged( ) method that is
invoked when an
adjustment event occurs. Its general form is shown here:
void adjustmentValueChanged(AdjustmentEvent ae)

3.ComponentListener 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(ComponentEvent ce)
void componentMoved(ComponentEvent ce)
void componentShown(ComponentEvent ce)
void componentHidden(ComponentEvent ce)

4.ContainerListener Interface:-
This interface contains 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 shown here:
void componentAdded(ContainerEvent ce)
void componentRemoved(ContainerEvent ce)

5.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 general forms are shown here:
void focusGained(FocusEvent fe)
void focusLost(FocusEvent fe)

6.ItemListener Interface:-
This interface defines the itemStateChanged( ) method that is invoked
when the state of an
item changes.
Its general form is shown here:
void itemStateChanged(ItemEvent ie)

7.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)
8.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 shown here:
void mouseClicked(MouseEvent me)
void mouseEntered(MouseEvent me)
void mouseExited(MouseEvent me)
void mousePressed(MouseEvent me)
void mouseReleased(MouseEvent me)

9.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 shown here:
void mouseDragged(MouseEvent me)
void mouseMoved(MouseEvent me)

10.MouseWheelListener Interface:-
This interface defines the mouseWheelMoved( ) method that is invoked
when the mouse
wheel is moved.
Its general form is shown here:
void mouseWheelMoved(MouseWheelEvent mwe)

11.TextListener Interface:-
This interface defines the textChanged( ) method that is invoked when a
change occurs
in a text area or text field.
Its general form is shown here:
void textChanged(TextEvent te)

12.WindowFocusListener Interface:-
This interface defines two methods: windowGainedFocus( ) and
windowLostFocus( ). These
are called when a window gains or loses input focus.
Their general forms are shown here:
void windowGainedFocus(WindowEvent we)
void windowLostFocus(WindowEvent we)
13.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)

You might also like