0% found this document useful (0 votes)
12 views

UNIT III Event Handling

Uploaded by

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

UNIT III Event Handling

Uploaded by

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

UNIT – III

EVENT HANDLING
Unit Outcomes (UOs): -

3a. Use delegation event model for given problem .


3b.Use AWT/Swing component(s) to handle given event.
3c.Use Adapter classes to solve the problem.
3d. Use Inner Classes to solve given problem.

Total Marks=12
UNIT-III EVENT HANDING
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.

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
received, the listener processes the event and then returns.

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.
The Delegation Event Model:
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.
PART-II [unit-III]
Advance JAVA Programming (22517)
Computer Engineering / IT Program Group (CO/CM/IF/CW)

Mrs. Manjula Athani HOD -


Computer Engineering
Email: [email protected]
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 example,
the method that registers a keyboard event listener is called addKeyListener( ).
The method that registers a mouse motion listener is called addMouseMotionListener( ).
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 Sources

 An event source is the object that generates the event. For example if you click a
button an ActionEvent object is generated.
 The object of the ActionEvent class has all corresponding information about this
event. Here button is an event source.
 Various event sources can be button, checkbox, textbox, scrollbars and so on.
 Event Listeners

 The task of handling an event is carried out by event listener.

 When an event occurs, first of all an event object of the appropriate type is created.
This object is then passed to a Listener.
 A listener must implement the interface that has the method for event handling.
 The java.awt.event package contains definitions of all event classes and listener
interface.
 An Interface contains constant values and method declaration.
 The methods in an interface are only declared and not implemented, i.e. the methods do
not have a body.

 The interfaces are used to define behaviour on occurrence of event that can be
implemented by any class anywhere in the class hierarchy.
 Event Classes

 Event classes are the classes responsible for handling events in the event handling
mechanism.
 The EventObject class is at the top of the event class hierarchy. It belongs to the
java.util package. And other event classes are present in java.awt.event package.
 The getSource() and toString() are the methods of the EventObject class.
 There is getId() method belonging to java.awt.event
For example, if a keyboard event occurs, you can find out whether the event was key
press or key release from the event object.
java.awt.event
PART-III [unit-III]
Advance JAVA Programming (22517)
Computer Engineering / IT Program Group (CO/CM/IF/CW)

Mrs. Manjula Athani HOD -


Computer Engineering
Email: [email protected]
 Various event classes that are defined in java.awt.event class are -

1. An ActionEvent object is generated when a component is activated. For example if


a button is pressed or a menu item is selected then this event occurs.
2. An AdjustmentEvent object is generated when scrollbars are used.
3. A TextEvent object is generated when text of a component or a text field is changed.
4. A ContainerEvent object is generated when component are added or removed from
container.
5. A ComponentEvent object is generated when a component is resized, moved,
hidden or made visible.
1. An ItemEvent is generated when an item from a list is selected. For example a
choice is made or if checkbox is selected.
2. A FocusEvent object is generated when component receives keyboard focus
for input.
3. A KeyEvent object is generated when key on keyboard is pressed or released.
4. A WindowEvent object is generated when a window activated, maximized or
minimized.
5. A MouseEvent object is generated when a mouse is clicked, moved, dragged,
released.
PART-IV [unit-III]
Advance JAVA Programming (22517)
Computer Engineering / IT Program Group (CO/CM/IF/CW)

Manjula Athani
HOD - Computer Engineering
Email: [email protected]
 ActionEvent Class

Description When an event gets generated due to pressing of button, or by


selecting menu item or by selecting an item, this event occurs.

Constructors ActionEvent(Object source, int id, string command, long when, int
modifier) The source indicates the object due to which the event is
generated.
The id which is used to identify the type of event.

The command is a string that specifies the command that is associated with
the event.
The when denotes the time of event.

The modifier indicates the modifier keys such as ALT, CNTRL, SHIFT that
are pressed when an event occurs.

Methods  String getActionCommand() : This method is useful for obtaining the


command string which is specified during the generation of event.
 int getModifiers() : This method returns the value which indicates the
type of key being pressed at the time of event.
 long getWhen() : It returns the time at which the event occurs.

Constants There are four constants that are used to indicate the modifier keys being
pressed. These constants are CTRL_MASK, SHIFT_MASK, META_MASK
and ALT_MASK.
 ItemEvent Class

Description This event gets caused when an item is selected or deselected.

Constructors ItemEvent(ItemSelectable, int, Object, int)

Constructs a ItemSelectEvent object with the specified ItemSelectable source,


type, item and item select state.

Methods 1) getItem() : It returns the item where the event occurred.


2) getItemSelectable() : Returns the ItemSelectable object where this event
originated.
3) getStateChange() : Returns the state change type which generated the
event.

Constants 1) ITEM_FIRST : Marks the first integer id for the range of item

2) ITEM_LAST : Marks the last integer id for the range of item

3) ITEM_STATE_CHANGED : The item state changed event type

4) SELECTED : The item selected state change type

5) DESELECTED : The item de-selected state change type


 KeyEvent Class

Description This event is generated when key on the keyboard is pressed or


released.

Constructors KeyEvent(Component source, int type, long t, int modifiers, int


code) The source is a reference to the component that generates the
event. The type specifies the type of event.
The t denotes the system time at which the event occurs.

The modifiers represent the modifier keys such as ALT, CNTRL,


SHIFT that are pressed when an event occurs.

The code represents the virtual keycode such as VK_UP, VK_ESCAPE and
so on

Methods  char getKeyChar() : It returns the character when a key is pressed.

Constants  KEY_PRESSED: This event is generated when the key is pressed.


 KEY_RELEASED: This event is generated when the key is released.
 KEY_TYPED: This event is generated when the key is typed.
 MouseEvent Class

Description This event occurs when mouse action occurs in a component. It reacts for both
mouse event and mouse motion event.
 Mouse Events

o A mouse button is pressed


o A mouse button is released
o A mouse button is clicked (pressed and released)
o The mouse cursor enters a component
o The mouse cursor exits a component
 Mouse Motion Events

o The mouse is moved


o The mouse is dragged
Methods 1) int getButton() : It returns which of the mouse button has changed the state.
2) int getClickCount() : It returns number of mouse clicks.

3) Point getLocationOnScreen() : Returns the absolute x, y position at that


event.
4) Point getPoint() : Returns the x,y position of the event relative to the source
component.
5) int getX() : Returns the horizontal x position of the event relative to the
source component.
6) int getY() : Returns the vertical y position of the event relative to the source
component.
Following are the fields for java.awt.event.MouseEvent class :
 static int MOUSE_CLICKED --The "mouse clicked" event
 static int MOUSE_DRAGGED --The "mouse dragged" event
 static int MOUSE_ENTERED --The "mouse entered" event
 static int MOUSE_EXITED --The "mouse exited" event

 static int MOUSE_MOVED --The "mouse moved" event


 static int MOUSE_PRESSED -- The "mouse pressed" event
 static int MOUSE_RELEASED --The "mouse released" event
 TextEvent Class

Description This event indicates that object's text is changed.

Constructor TextEvent(Object source, int id) It


constructs a TextEvent object.

Methods String paramString() : Returns a parameter string identifying this


text event.

Fields  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.
 WindowEvent Class

Description This is an event that indicates that a window has changed its status.

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.

Methods 1) int getNewState() : It returns the new state of the window.

2) int getOldState() : It returns the previous state of the window.

3) Window getOppositeWindow() : Returns the other Window


involved in this focus or activation change.
4) Window getWindow() : Returns the originator of the event.
 WindowEvent Class

Description This is an event that indicates that a window has changed its status.

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.

Methods 1) int getNewState() : It returns the new state of the window.

2) int getOldState() : It returns the previous state of the window.

3) Window getOppositeWindow() : Returns the other Window


involved in this focus or activation change.
4) Window getWindow() : Returns the originator of the event.
 Keyboard Events.
When key from a keyboard is pressed then it causes an event. There are three
commonly used methods from KeyListener interface and those are keyPressed(),
keyReleased() and keyTyped().

1) The keyPressed() event is for handling the event of pressing a key, similarly
keyReleased() event is for handling the event of release of key.
2) Using keyTyped() method we can display the character typed on the screen. The
only needed method for this is getKeyChar() which returns the currently typed
character.
PART-V [unit-III]
Advance JAVA Programming (22517)
Computer Engineering / IT Program Group (CO/CM/IF/CW)

Mrs. Manjula Athani


HOD - Computer Engineering
Email: [email protected]
 EventListener Interfaces

 The task of handling an event is carried out by event listener.

 When an event occurs, first of all an event object of the appropriate type is created. This object is then passed to a
Listener.
 A listener must implement the interface that has the method for event handling.
 The java.awt.event package contains definitions of all event classes and listener interface.
 An Interface contains constant values and method declaration.
 The methods in an interface are only declared and not implemented, i.e. the methods do not have a body.
 The interfaces are used to define behavior on occurrence of event that can be implemented by any class anywhere in the
class hierarchy.
 ActionListener Interface

 This interface defines the method actionPerformed() which is invoked when an ActionEvent occurs.
 The syntax of this method is

void actionPerformed(ActionEvent act)

where act is an object of ActionEvent class.


 ItemListener Interface

 This interface is used when an item from a list is selected. For example a choice is made or
if checkbox is selected.
 The itemStateChanged() is the only method defined by the ItemListener interface.
 The syntax is

void itemStateChanged(ItemEvent It)


 KeyListener Interface

 This interface is defining the events such as keyPressed(), keyReleased() and keyTyped()
are used.
 These methods are useful for key press, key release and when you type some characters.
void keyPressed(keyEvent k)

void keyReleased(keyEvent k)
void keyTyped(keyEvent k)
 MouseListener Interface

 This interface defines five important methods for various activities such as mouse click, press, released,
entered or exited. These are
void mouseClicked(MouseEvent m)
void mousePressed(MouseEvent m)
void mouseReleased(MouseEvent m)
void mouseEntered(MouseEvent m)
void mouseExited(MouseEvent m)

Methods of MouseMotionListener interface


The signature of 2 methods found in MouseMotionListener interface are given below:

void mouseDragged(MouseEvent e);


void mouseMoved(MouseEvent e);
 MouseMotion Interface

For handling mouse drag and mouse move events the required methods are defined by
MouseMotionListener interface. These methods are

void mouseDragged(MouseEvent m)
void mouseMoved(MouseEvent m)
 TextListener Interface
An event of type TextEvent is generated when a value in textfield or textarea is entered
or edited.
The methods used by TextListener Interface are
public String paramString():

public void textValueChanged(TextEvent e):


 WindowListener Interface

There are seven methods in which are related to windows activation and deactivation.
void windowOpened(WindowEvent w)

void windowClosed(WindowEvent w)

void windowClosing(WindowEvent w)

void windowActivated(WindowEvent w)

void windowDeactivated(WindowEvent w)

void windowIconified(WindowEvent w)

void windowDeiconified(WindowEvent w)
PART-VI [unit-III]
Advance JAVA Programming (22517)
Computer Engineering / IT Program Group (CO/CM/IF/CW)

Mrs. Manjula Athani


HOD - Computer Engineering
Email: [email protected]
⮚ Adapter Classes

∙ It is basically a class in Java that implements an interface with a set of dummy methods.
∙ The famous adapter classes in Java API are WindowAdapter, ComponentAdapter,
ContainerAdapter, FocusAdapter, KeyAdapter, MouseAdapter and
MouseMotionAdapter.
∙ Whenever your class implements such interface, you have to implements all of the seven
methods.
∙ WindowAdapter class implements WindowListener interface and make seven empty
implementation.
Inner classes:
Java inner class is a class within class is called inner class or interface.
Without existing one type of object there is no chance of existing another type of object then we should go for
inner class.
Example: University consists of several departments without existing university there is no chance of
existing department hence we have to declare department class inside university class.

class university OUTER CLASS


{
class department INNER CLASS
{

}
}
NOTE:WITHOUT EXISTING OUTER CLASS OBJECT THERE IS NO CHANCE OF EXISTING INNER CLASS OBJECT
.
Based on position of declaration and behavior all Inner lasses are devided into 4 types.
1.Normal inner class
2.Method Local inner class
3.Anonymous inner class
4.Static nested class
1.Normal inner class: If you are declaring any named class directly inside a class
without static modifiers such type of inner class is called normal inner class.

Class Outer
{
Class Inner
{

}
}
Internal working of Java member inner class
The java compiler creates two class files in case of inner class. The class file name of inner
class is "Outer$Inner". If you want to instantiate inner class, you must have to create the
instance of outer class. In such case, instance of inner class is created inside the instance of
outer class.

After compiling i.e


Javac Outer.java
Creates two class files 1.Outer.class 2.Outer$Inner.class
Method local Inner classes.
Sometimes we can declare a class inside a method such type of Inner classes are called method Local Inner classes.
The main purpose of method local inner class is to define method specific repeatedly required functionality method. Local
method inner classes are best suitable to meet nested method requirement

public class MethodLocal {


public void m1(){
class Inner {
public void sum(int x,int y)
{
System.out.println("The SUM:"+(x+y));
}
}
Inner i=new Inner();
i.sum(10,20); i.sum(100,200); i.sum(1000,2000);
}
public static void main(String args[])
{
MethodLocal m=new MethodLocal();
m.m1();
} }
Java Anonymous inner class
Sometimes we can declare inner class without name such type inner classes are called anonymous Inner classes.

The main purpose of anonymous inner class is just use of one time usage.
Java anonymous inner class example using class
abstract class Person{
abstract void eat();
}
class TestAnonymousInner
{
public static void main(String args[])
{
Person p=new Person()
{
void eat()
{
System.out.println("nice fruits");}
};
p.eat();
}
}
Java static nested class
A static class i.e. created inside a class is called static nested class in java. It cannot access non-static data members
and methods. It can be accessed by outer class name.
It can access static data members of outer class including private.
Static nested class cannot access non-static (instance) data member or method.
Java static nested class example with instance method
class TestOuter1
{
static int data=30;
static class Inner{
void msg()
{
System.out.println("data is "+data);}
}
public static void main(String args[])
{
TestOuter1.Inner obj=new TestOuter1.Inner();
obj.msg();
}
}
Output:
data is 30

You might also like