SlideShare uma empresa Scribd logo
1 de 17
Event Handling
Event and Listener (Java Event Handling)
Changing the state of an object is known as an event. For example, click on button,
dragging mouse etc. The java.awt.event package provides many event classes and
Listener interfaces for event handling.
Types of Event
The events can be broadly classified into two categories:
 Foreground Events - Those events which require the direct interaction of
user.They are generated as consequences of a person interacting with the graphical
components in Graphical User Interface. For example, clicking on a button, moving
the mouse, entering a character through keyboard,selecting an item from list,
scrolling the page etc.
 Background Events - Those events that require the interaction of end user are
known as background events. Operating system interrupts, hardware or software
failure, timer expires, an operation completion are the example of background
events.
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. This model
defines the standard mechanism to generate and handle the events.Let's have a brief introduction
to this model.
The Delegation Event Model has the following key participants namely:
 Source - The source is an object on which event occurs. Source is responsible for providing
information of the occurred event to it's handler. Java provide as with classes for source
object.
 Listener - It is also known as event handler. Listener is responsible for generating response
to an event. From java implementation point of view the listener is also an object. Listener
waits until it receives an event. Once the event is received , the listener process the event an
then returns.
L 2.1
Event Listeners
• A listener is an object that is notified when an event occurs.
• Event has two major requirements.
1. It must have been registered with one or more sources to receive
notifications about specific types of events.
2. 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.
Steps to perform Event Handling
Register the component with the Listener
For registering the component with the Listener, many classes provide the registration methods.
For example:
o Button
o public void addActionListener(ActionListener a){}
o MenuItem
o public void addActionListener(ActionListener a){}
o TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
o TextArea
o public void addTextListener(TextListener a){}
o Checkbox
o public void addItemListener(ItemListener a){}
o Choice
o public void addItemListener(ItemListener a){}
o List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}
For the understanding purpose, we will be looking at the ActionListener as it is the most
commonly used event listener and see how exactly it handles the events.
//Java event handling by implementing ActionListener
import java.awt.*;
import java.awt.event.*;
class EventHandle extends Frame implements ActionListener{
TextField textField;
EventHandle()
{
textField = new TextField();
textField.setBounds(60,50,170,20);
Button button = new Button("Quote");
button.setBounds(90,140,75,40);
//1
button.addActionListener(this);
add(button);
add(textField);
setSize(250,250);
setLayout(null);
setVisible(true);
}
//2
public void actionPerformed(ActionEvent e){
textField.setText("Keep Learning");
}
public static void main(String args[]){
new EventHandle();
}
} (1) (2)
Image 1 shows the output of our code when the state of the button was unclicked. Image 2
shows the output after the button is pressed.
Now, look at the code I’ve divided it into 2 important parts. Int the first part we are
registering our button object with the ActionListener. This is done by calling the
addActionListener( ) method and passing current instance using ‘this’ keyword.
Once we have registered our button with the ActionListener now we need to override
the actionPerformed( ) method which takes an object of class ActionEvent.
Delegation Event Model
We know about Source, Listener, and Event. Now let’s look at the model which joins these 3
entities and make them work in sync. The delegation event model is used to accomplish the
task. It consists of 2 components Source and listener. As soon as the source generates an
event it is noticed by the listener and it handles the event at hand. For this action to happen
the component or the source should be registered with the listener so that it can be notified
when an event occurs.
The specialty of delegation Event Model is that the GUI component passes the event
processing part to a completely separate set of code.
Event Methods to ‘Override’ EvenListener
ActionEvent- Events
generated from buttons,
menu items, etc.
actionPerformed(ActionEvent
e)
ActionListener
KeyEvent- Events generaated
when input is received from
the keyboard.
keyPressed(KeyEvent ke)
keyTyped(KeyEvent ke)
keyReleased(KeyEvent ke)
KeyListener
ItemEvent- Events generated
from List, Radio Button, etc.
itemStateChanged(ItemEvent
ie )
ItemListener
MouseEvent– Event
generated by the mouse
mouseMoved(MouseEvent
me)
mouseDragged(MouseEvent
me)
MouseMotionListener
List Of Listeners
Delegation Event Model
We know about Source, Listener, and Event. Now let’s look at the model which joins
these 3 entities and make them work in sync. The delegation event model is used to
accomplish the task. It consists of 2 components Source and listener. As soon as the
source generates an event it is noticed by the listener and it handles the event at
hand. For this action to happen the component or the source should be registered
with the listener so that it can be notified when an event occurs.
The specialty of delegation Event Model is that the GUI component passes the
event processing part to a completely separate set of code.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.applet.*;
import java.awt.event.*;
import java.awt.*;
public class Test extends Applet implements KeyListener
{
String msg="";
public void init()
{
addKeyListener(this);
}
public void keyPressed(KeyEvent k)
{
showStatus("KeyPressed");
}
public void keyReleased(KeyEvent k)
{
showStatus("KeyRealesed");
}
public void keyTyped(KeyEvent k)
{
msg = msg+k.getKeyChar();
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg, 20, 40);
}
}
Java MouseListener Interface
The Java MouseListener is notified whenever you change the state of mouse. It is notified
against MouseEvent. The MouseListener interface is found in java.awt.event package. It
has five methods.
Methods of MouseListener interface
The signature of 5 methods found in MouseListener interface are given below:
1. public abstract void mouseClicked(MouseEvent e);
2. public abstract void mouseEntered(MouseEvent e);
3. public abstract void mouseExited(MouseEvent e);
4. public abstract void mousePressed(MouseEvent e);
5. public abstract void mouseReleased(MouseEvent e);
import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample extends Frame implements MouseListener{
Label l;
MouseListenerExample()
{
addMouseListener(this);
l=new Label();
l.setBounds(20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e)
{
l.setText("Mouse Clicked");
}
public void mouseEntered(MouseEvent e)
{
l.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e)
{
l.setText("Mouse Exited");
}
public void mousePressed(MouseEvent e)
{
l.setText("Mouse Pressed");
}
public void mouseReleased(MouseEvent e)
{
l.setText("Mouse Released");
}
public static void main(String[] args) {
new MouseListenerExample();
} }
L 3.3
Adapter classes
• Java provides a special feature, called an adapter class, that
can simplify the creation of event handlers.
• 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.
L 3.4
• adapter classes in java.awt.event are.
Adapter Class Listener Interface
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
FocusAdapter FocusListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
WindowAdapter WindowListener
L 3.5
Inner classes
• Inner classes, which allow one class to be defined within
another.
• 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.
• An inner class is fully within the scope of its enclosing class.
• an inner class has access to all of the members of its enclosing
class, but the reverse is not true.
• Members of the inner class are known only within the scope
of the inner class and may not be used by the outer class

Mais conteúdo relacionado

Mais procurados (20)

Applets
AppletsApplets
Applets
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Abstract data types
Abstract data typesAbstract data types
Abstract data types
 
JAVA PROGRAMMING- GUI Programming with Swing - The Swing Buttons
JAVA PROGRAMMING- GUI Programming with Swing - The Swing ButtonsJAVA PROGRAMMING- GUI Programming with Swing - The Swing Buttons
JAVA PROGRAMMING- GUI Programming with Swing - The Swing Buttons
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
First and follow set
First and follow setFirst and follow set
First and follow set
 
input/ output in java
input/ output  in javainput/ output  in java
input/ output in java
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
System calls
System callsSystem calls
System calls
 
Java package
Java packageJava package
Java package
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Event Handling in JAVA
Event Handling in JAVAEvent Handling in JAVA
Event Handling in JAVA
 
GUI components in Java
GUI components in JavaGUI components in Java
GUI components in Java
 
Java Networking
Java NetworkingJava Networking
Java Networking
 
Exception handling
Exception handlingException handling
Exception handling
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Threads in JAVA
 
Hashing
HashingHashing
Hashing
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Java layoutmanager
Java layoutmanagerJava layoutmanager
Java layoutmanager
 
Java applets
Java appletsJava applets
Java applets
 

Semelhante a Event handling

Ajp notes-chapter-03
Ajp notes-chapter-03Ajp notes-chapter-03
Ajp notes-chapter-03Ankit Dubey
 
Event Handling in Java
Event Handling in JavaEvent Handling in Java
Event Handling in JavaAyesha Kanwal
 
tL20 event handling
tL20 event handlingtL20 event handling
tL20 event handlingteach4uin
 
engineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.pptengineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.pptsharanyak0721
 
Advance Java Programming(CM5I) Event handling
Advance Java Programming(CM5I) Event handlingAdvance Java Programming(CM5I) Event handling
Advance Java Programming(CM5I) Event handlingPayal Dungarwal
 
Dr Jammi Ashok - Introduction to Java Material (OOPs)
 Dr Jammi Ashok - Introduction to Java Material (OOPs) Dr Jammi Ashok - Introduction to Java Material (OOPs)
Dr Jammi Ashok - Introduction to Java Material (OOPs)jammiashok123
 
event-handling.pptx
event-handling.pptxevent-handling.pptx
event-handling.pptxGood657694
 
event-handling.pptx
event-handling.pptxevent-handling.pptx
event-handling.pptxusvirat1805
 
Java gui event
Java gui eventJava gui event
Java gui eventSoftNutx
 
ITE 1122_ Event Handling.pptx
ITE 1122_ Event Handling.pptxITE 1122_ Event Handling.pptx
ITE 1122_ Event Handling.pptxudithaisur
 
Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024nehakumari0xf
 
Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024kashyapneha2809
 
Unit-3 event handling
Unit-3 event handlingUnit-3 event handling
Unit-3 event handlingAmol Gaikwad
 
event handling new.ppt
event handling new.pptevent handling new.ppt
event handling new.pptusama537223
 

Semelhante a Event handling (20)

Ajp notes-chapter-03
Ajp notes-chapter-03Ajp notes-chapter-03
Ajp notes-chapter-03
 
Unit 6 Java
Unit 6 JavaUnit 6 Java
Unit 6 Java
 
What is Event
What is EventWhat is Event
What is Event
 
Event Handling in Java
Event Handling in JavaEvent Handling in Java
Event Handling in Java
 
tL20 event handling
tL20 event handlingtL20 event handling
tL20 event handling
 
engineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.pptengineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.ppt
 
Advance Java Programming(CM5I) Event handling
Advance Java Programming(CM5I) Event handlingAdvance Java Programming(CM5I) Event handling
Advance Java Programming(CM5I) Event handling
 
Lecture8 oopj
Lecture8 oopjLecture8 oopj
Lecture8 oopj
 
Dr Jammi Ashok - Introduction to Java Material (OOPs)
 Dr Jammi Ashok - Introduction to Java Material (OOPs) Dr Jammi Ashok - Introduction to Java Material (OOPs)
Dr Jammi Ashok - Introduction to Java Material (OOPs)
 
Event handling in Java(part 1)
Event handling in Java(part 1)Event handling in Java(part 1)
Event handling in Java(part 1)
 
event-handling.pptx
event-handling.pptxevent-handling.pptx
event-handling.pptx
 
event-handling.pptx
event-handling.pptxevent-handling.pptx
event-handling.pptx
 
Java gui event
Java gui eventJava gui event
Java gui event
 
09events
09events09events
09events
 
ITE 1122_ Event Handling.pptx
ITE 1122_ Event Handling.pptxITE 1122_ Event Handling.pptx
ITE 1122_ Event Handling.pptx
 
Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024
 
Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024
 
Unit-3 event handling
Unit-3 event handlingUnit-3 event handling
Unit-3 event handling
 
event handling new.ppt
event handling new.pptevent handling new.ppt
event handling new.ppt
 
Java
JavaJava
Java
 

Mais de swapnac12

Awt, Swing, Layout managers
Awt, Swing, Layout managersAwt, Swing, Layout managers
Awt, Swing, Layout managersswapnac12
 
Asymptotic notations(Big O, Omega, Theta )
Asymptotic notations(Big O, Omega, Theta )Asymptotic notations(Big O, Omega, Theta )
Asymptotic notations(Big O, Omega, Theta )swapnac12
 
Performance analysis(Time & Space Complexity)
Performance analysis(Time & Space Complexity)Performance analysis(Time & Space Complexity)
Performance analysis(Time & Space Complexity)swapnac12
 
Introduction ,characteristics, properties,pseudo code conventions
Introduction ,characteristics, properties,pseudo code conventionsIntroduction ,characteristics, properties,pseudo code conventions
Introduction ,characteristics, properties,pseudo code conventionsswapnac12
 
Inductive analytical approaches to learning
Inductive analytical approaches to learningInductive analytical approaches to learning
Inductive analytical approaches to learningswapnac12
 
Using prior knowledge to initialize the hypothesis,kbann
Using prior knowledge to initialize the hypothesis,kbannUsing prior knowledge to initialize the hypothesis,kbann
Using prior knowledge to initialize the hypothesis,kbannswapnac12
 
Combining inductive and analytical learning
Combining inductive and analytical learningCombining inductive and analytical learning
Combining inductive and analytical learningswapnac12
 
Analytical learning
Analytical learningAnalytical learning
Analytical learningswapnac12
 
Learning set of rules
Learning set of rulesLearning set of rules
Learning set of rulesswapnac12
 
Learning rule of first order rules
Learning rule of first order rulesLearning rule of first order rules
Learning rule of first order rulesswapnac12
 
Genetic algorithms
Genetic algorithmsGenetic algorithms
Genetic algorithmsswapnac12
 
Instance based learning
Instance based learningInstance based learning
Instance based learningswapnac12
 
Computational learning theory
Computational learning theoryComputational learning theory
Computational learning theoryswapnac12
 
Multilayer & Back propagation algorithm
Multilayer & Back propagation algorithmMultilayer & Back propagation algorithm
Multilayer & Back propagation algorithmswapnac12
 
Artificial Neural Networks 1
Artificial Neural Networks 1Artificial Neural Networks 1
Artificial Neural Networks 1swapnac12
 
Evaluating hypothesis
Evaluating  hypothesisEvaluating  hypothesis
Evaluating hypothesisswapnac12
 
Advanced topics in artificial neural networks
Advanced topics in artificial neural networksAdvanced topics in artificial neural networks
Advanced topics in artificial neural networksswapnac12
 
Introdution and designing a learning system
Introdution and designing a learning systemIntrodution and designing a learning system
Introdution and designing a learning systemswapnac12
 
Inductive bias
Inductive biasInductive bias
Inductive biasswapnac12
 

Mais de swapnac12 (20)

Awt, Swing, Layout managers
Awt, Swing, Layout managersAwt, Swing, Layout managers
Awt, Swing, Layout managers
 
Applet
 Applet Applet
Applet
 
Asymptotic notations(Big O, Omega, Theta )
Asymptotic notations(Big O, Omega, Theta )Asymptotic notations(Big O, Omega, Theta )
Asymptotic notations(Big O, Omega, Theta )
 
Performance analysis(Time & Space Complexity)
Performance analysis(Time & Space Complexity)Performance analysis(Time & Space Complexity)
Performance analysis(Time & Space Complexity)
 
Introduction ,characteristics, properties,pseudo code conventions
Introduction ,characteristics, properties,pseudo code conventionsIntroduction ,characteristics, properties,pseudo code conventions
Introduction ,characteristics, properties,pseudo code conventions
 
Inductive analytical approaches to learning
Inductive analytical approaches to learningInductive analytical approaches to learning
Inductive analytical approaches to learning
 
Using prior knowledge to initialize the hypothesis,kbann
Using prior knowledge to initialize the hypothesis,kbannUsing prior knowledge to initialize the hypothesis,kbann
Using prior knowledge to initialize the hypothesis,kbann
 
Combining inductive and analytical learning
Combining inductive and analytical learningCombining inductive and analytical learning
Combining inductive and analytical learning
 
Analytical learning
Analytical learningAnalytical learning
Analytical learning
 
Learning set of rules
Learning set of rulesLearning set of rules
Learning set of rules
 
Learning rule of first order rules
Learning rule of first order rulesLearning rule of first order rules
Learning rule of first order rules
 
Genetic algorithms
Genetic algorithmsGenetic algorithms
Genetic algorithms
 
Instance based learning
Instance based learningInstance based learning
Instance based learning
 
Computational learning theory
Computational learning theoryComputational learning theory
Computational learning theory
 
Multilayer & Back propagation algorithm
Multilayer & Back propagation algorithmMultilayer & Back propagation algorithm
Multilayer & Back propagation algorithm
 
Artificial Neural Networks 1
Artificial Neural Networks 1Artificial Neural Networks 1
Artificial Neural Networks 1
 
Evaluating hypothesis
Evaluating  hypothesisEvaluating  hypothesis
Evaluating hypothesis
 
Advanced topics in artificial neural networks
Advanced topics in artificial neural networksAdvanced topics in artificial neural networks
Advanced topics in artificial neural networks
 
Introdution and designing a learning system
Introdution and designing a learning systemIntrodution and designing a learning system
Introdution and designing a learning system
 
Inductive bias
Inductive biasInductive bias
Inductive bias
 

Último

The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...anjaliyadav012327
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 

Último (20)

The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 

Event handling

  • 1. Event Handling Event and Listener (Java Event Handling) Changing the state of an object is known as an event. For example, click on button, dragging mouse etc. The java.awt.event package provides many event classes and Listener interfaces for event handling. Types of Event The events can be broadly classified into two categories:  Foreground Events - Those events which require the direct interaction of user.They are generated as consequences of a person interacting with the graphical components in Graphical User Interface. For example, clicking on a button, moving the mouse, entering a character through keyboard,selecting an item from list, scrolling the page etc.  Background Events - Those events that require the interaction of end user are known as background events. Operating system interrupts, hardware or software failure, timer expires, an operation completion are the example of background events.
  • 2. 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. This model defines the standard mechanism to generate and handle the events.Let's have a brief introduction to this model. The Delegation Event Model has the following key participants namely:  Source - The source is an object on which event occurs. Source is responsible for providing information of the occurred event to it's handler. Java provide as with classes for source object.  Listener - It is also known as event handler. Listener is responsible for generating response to an event. From java implementation point of view the listener is also an object. Listener waits until it receives an event. Once the event is received , the listener process the event an then returns.
  • 3. L 2.1 Event Listeners • A listener is an object that is notified when an event occurs. • Event has two major requirements. 1. It must have been registered with one or more sources to receive notifications about specific types of events. 2. 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.
  • 4. Steps to perform Event Handling Register the component with the Listener For registering the component with the Listener, many classes provide the registration methods. For example: o Button o public void addActionListener(ActionListener a){} o MenuItem o public void addActionListener(ActionListener a){} o TextField o public void addActionListener(ActionListener a){} o public void addTextListener(TextListener a){} o TextArea o public void addTextListener(TextListener a){} o Checkbox o public void addItemListener(ItemListener a){} o Choice o public void addItemListener(ItemListener a){} o List o public void addActionListener(ActionListener a){}
  • 5. o public void addItemListener(ItemListener a){} For the understanding purpose, we will be looking at the ActionListener as it is the most commonly used event listener and see how exactly it handles the events. //Java event handling by implementing ActionListener import java.awt.*; import java.awt.event.*; class EventHandle extends Frame implements ActionListener{ TextField textField; EventHandle() { textField = new TextField(); textField.setBounds(60,50,170,20); Button button = new Button("Quote"); button.setBounds(90,140,75,40); //1 button.addActionListener(this); add(button); add(textField); setSize(250,250); setLayout(null); setVisible(true); }
  • 6. //2 public void actionPerformed(ActionEvent e){ textField.setText("Keep Learning"); } public static void main(String args[]){ new EventHandle(); } } (1) (2)
  • 7. Image 1 shows the output of our code when the state of the button was unclicked. Image 2 shows the output after the button is pressed. Now, look at the code I’ve divided it into 2 important parts. Int the first part we are registering our button object with the ActionListener. This is done by calling the addActionListener( ) method and passing current instance using ‘this’ keyword. Once we have registered our button with the ActionListener now we need to override the actionPerformed( ) method which takes an object of class ActionEvent. Delegation Event Model We know about Source, Listener, and Event. Now let’s look at the model which joins these 3 entities and make them work in sync. The delegation event model is used to accomplish the task. It consists of 2 components Source and listener. As soon as the source generates an event it is noticed by the listener and it handles the event at hand. For this action to happen the component or the source should be registered with the listener so that it can be notified when an event occurs. The specialty of delegation Event Model is that the GUI component passes the event processing part to a completely separate set of code.
  • 8. Event Methods to ‘Override’ EvenListener ActionEvent- Events generated from buttons, menu items, etc. actionPerformed(ActionEvent e) ActionListener KeyEvent- Events generaated when input is received from the keyboard. keyPressed(KeyEvent ke) keyTyped(KeyEvent ke) keyReleased(KeyEvent ke) KeyListener ItemEvent- Events generated from List, Radio Button, etc. itemStateChanged(ItemEvent ie ) ItemListener MouseEvent– Event generated by the mouse mouseMoved(MouseEvent me) mouseDragged(MouseEvent me) MouseMotionListener List Of Listeners
  • 9. Delegation Event Model We know about Source, Listener, and Event. Now let’s look at the model which joins these 3 entities and make them work in sync. The delegation event model is used to accomplish the task. It consists of 2 components Source and listener. As soon as the source generates an event it is noticed by the listener and it handles the event at hand. For this action to happen the component or the source should be registered with the listener so that it can be notified when an event occurs. The specialty of delegation Event Model is that the GUI component passes the event processing part to a completely separate set of code.
  • 10. import java.awt.*; import java.awt.event.*; import java.applet.*; import java.applet.*; import java.awt.event.*; import java.awt.*; public class Test extends Applet implements KeyListener { String msg=""; public void init() { addKeyListener(this); } public void keyPressed(KeyEvent k) { showStatus("KeyPressed"); } public void keyReleased(KeyEvent k) { showStatus("KeyRealesed"); }
  • 11. public void keyTyped(KeyEvent k) { msg = msg+k.getKeyChar(); repaint(); } public void paint(Graphics g) { g.drawString(msg, 20, 40); } }
  • 12. Java MouseListener Interface The Java MouseListener is notified whenever you change the state of mouse. It is notified against MouseEvent. The MouseListener interface is found in java.awt.event package. It has five methods. Methods of MouseListener interface The signature of 5 methods found in MouseListener interface are given below: 1. public abstract void mouseClicked(MouseEvent e); 2. public abstract void mouseEntered(MouseEvent e); 3. public abstract void mouseExited(MouseEvent e); 4. public abstract void mousePressed(MouseEvent e); 5. public abstract void mouseReleased(MouseEvent e);
  • 13. import java.awt.*; import java.awt.event.*; public class MouseListenerExample extends Frame implements MouseListener{ Label l; MouseListenerExample() { addMouseListener(this); l=new Label(); l.setBounds(20,50,100,20); add(l); setSize(300,300); setLayout(null); setVisible(true); } public void mouseClicked(MouseEvent e) { l.setText("Mouse Clicked"); } public void mouseEntered(MouseEvent e) { l.setText("Mouse Entered"); } public void mouseExited(MouseEvent e) { l.setText("Mouse Exited"); } public void mousePressed(MouseEvent e) { l.setText("Mouse Pressed"); } public void mouseReleased(MouseEvent e) { l.setText("Mouse Released"); }
  • 14. public static void main(String[] args) { new MouseListenerExample(); } }
  • 15. L 3.3 Adapter classes • Java provides a special feature, called an adapter class, that can simplify the creation of event handlers. • 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.
  • 16. L 3.4 • adapter classes in java.awt.event are. Adapter Class Listener Interface ComponentAdapter ComponentListener ContainerAdapter ContainerListener FocusAdapter FocusListener KeyAdapter KeyListener MouseAdapter MouseListener MouseMotionAdapter MouseMotionListener WindowAdapter WindowListener
  • 17. L 3.5 Inner classes • Inner classes, which allow one class to be defined within another. • 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. • An inner class is fully within the scope of its enclosing class. • an inner class has access to all of the members of its enclosing class, but the reverse is not true. • Members of the inner class are known only within the scope of the inner class and may not be used by the outer class