SlideShare a Scribd company logo
1 of 31
Download to read offline
Programming in Java
Event Handling
By
Ravi Kant Sahu
Asst. Professor

Lovely Professional University, Punjab
Outlines
•
•
•
•
•
•
•

Delegation Event Model
ActionListener
ItemListener
KeyListener
MouseListener
MouseMotionListener
WindowListener

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Introduction
• An event can be defined as a signal to the program that something has
happened.
• Events are triggered either by external user actions, such as mouse
movements, button clicks, and keystrokes, or by internal program
activities, such as a timer.
• The program can choose to respond to or ignore an event.
• The component that creates an event and fires it is called the source
object or source component.
• For example, a button is the source object for a button-clicking action
event.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Introduction
• An event is an instance of an event class.
• The root class of the event classes is java.util.EventObject.
•

We can identify the source object of an event using the getSource()
method in the EventObject class.

• The subclasses of EventObject deal with special types of events, such
as action events, window events, component events, mouse events,
and key events.

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Delegation event MoDel

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
The Delegation Event Model
• The delegation event model defines standard and consistent
mechanisms to generate and process events.

Principle:
• A source generates an event and sends it to one or more listeners.
• The listener waits until it receives an event.
• Once an event is received, the listener processes the event and then
returns.
Advantage:
• 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.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
• 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.

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Event
• 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.
• For Example, pressing a button, entering a character via the
keyboard, selecting an item in a list, and clicking the mouse.
• Events may also occur that are not directly caused by interactions
with a user interface.
• For example, an event may be generated when a timer expires, a
counter exceeds a value, a software or hardware failure occurs, or
an operation is completed.

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Event Source
• An Event 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.
public void addTypeListener(TypeListener el)
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
• When an event occurs, all registered listeners are notified and
receive a copy of the event object. This is known as multicasting
the event.
• In all cases, notifications are sent only to listeners that register to
receive them.
• Some sources may allow only one listener to register.
public void addTypeListener(TypeListener el) throws
java.util.TooManyListenersException

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Event Listener
• 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.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Listener interfaces

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Listener API Table
Listener Interface

Listener Methods

ActionListener

actionPerformed(ActionEvent)

ItemListener

itemStateChanged(ItemEvent)

MouseListener

mouseClicked(MouseEvent)
mouseEntered(MouseEvent)
mouseExited(MouseEvent)
mousePressed(MouseEvent)
mouseReleased(MouseEvent)

MouseMotionListener

KeyListener

mouseDragged(MouseEvent)
mouseMoved(MouseEvent)
keyPressed(KeyEvent)
keyReleased(KeyEvent)
keyTyped(KeyEvent)

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
ActionListener
• Action listeners are most common event handlers to implement.
• An action event occurs, whenever an action is performed by the user.
• We implement an action listener to define what should be done when
an user performs certain operation.
Examples: When the user clicks a button, chooses a menu item,
presses Enter in a text field.
•

The result is that an actionPerformed message is sent to all action
listeners that are registered on the relevant component.

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
• To write an Action Listener, follow the steps given below:
• Declare an event handler class and specify that the class either
implements an ActionListener interface or extends a class that
implements an ActionListener interface.
For example:
public class MyClass implements ActionListener {
• Register an instance of the event handler class as a listener on one
or more components.
For example:
someComponent.addActionListener(instanceOfMyClass);
• Include code that implements the methods in listener interface.
For example:
public void actionPerformed(ActionEvent e)
{ ...//code that reacts to the action... }
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
ActionEvent Class
Method

Purpose

String getActionCommand()

Returns the string associated with this
action. Most objects that can fire action
events support a method called
setActionCommand that lets you set
this string.

Object getSource()

Returns the object that fired the event.

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
ItemListener Interface
• Item events are fired by components that implement the
ItemSelectable interface.
• Generally, ItemSelectable components maintain on/off state for one or
more items.
• The Swing components that fire item events include buttons like
check boxes, check menu items, toggle buttons and combo boxes etc.
• ItemListener Interface has only one method.

public void itemStateChanged (ItemEvent)

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
ItemEvent class
Method
Object getItem()

Purpose
Returns the component-specific
object associated with the item
whose state changed. Often this is a
String containing the text on the
selected item.

ItemSelectable getItemSelectable() Returns the component that fired
the item event. You can use this
instead of the getSource method.
int getStateChange()

Returns the new state of the item.
The ItemEvent class defines two
states: SELECTED and
DESELECTED.

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
KeyListener Interface
• Key events indicate when the user is typing at the keyboard.
• Key events are fired by the component with the keyboard focus
when the user presses or releases keyboard keys.
• Notifications are sent about two basic kinds of key events:
– The typing of a Unicode character
– The pressing or releasing of a key on the keyboard

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
• The first kind of event is called a key-typed event.
• To know when the user types a Unicode character ? whether by
pressing one key such as 'a' or by pressing several keys in sequence ?
• The second kind is either a key-pressed or key-released event.
• To know when the user presses the F1 key, or whether the user
pressed the '3' key on the number pad, you handle key-pressed events.

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Methods of KeyListener Interface
Method

Purpose

keyTyped(KeyEvent)

Called just after the user types a
Unicode character into the listenedto component.

keyPressed(KeyEvent)

Called just after the user presses a
key while the listened-to
component has the focus.

keyReleased(KeyEvent)

Called just after the user releases a
key while the listened-to
component has the focus.

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
KeyEvent class
Method

int getKeyChar()

Purpose
Obtains the Unicode character associated
with this event.

int getKeyCode()

Obtains the key code associated with this
event. The key code identifies the
particular key on the keyboard that the user
pressed or released. For example, VK_A
specifies the key labeled A, and
VK_ESCAPE specifies the Escape key.

boolean isActionKey()

Returns true if the key firing the event is an
action key. Examples of action keys
include Page Up, Caps Lock, the arrow and
function keys.

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
MouseListener Interface
• Mouse events notify when the user uses the mouse (or similar input
device) to interact with a component.
• Mouse events occur when the cursor enters or exits a component's
onscreen area and when the user presses or releases one of the mouse
buttons.

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Methods of MouseListener Interface
Method

Purpose

mouseClicked(MouseEvent)

Called just after the user clicks the
listened-to component.

mouseEntered(MouseEvent)

Called just after the cursor enters
the bounds of the listened-to
component.

mouseExited(MouseEvent)

Called just after the cursor exits the
bounds of the listened-to
component.

mousePressed(MouseEvent)

Called just after the user presses a
mouse button while the cursor is
over the listened-to component.

mouseReleased(MouseEvent)

Called just after the user releases a
mouse button after a mouse press
over the listened-to component.

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
MouseEvent class
Method

Purpose

int getClickCount()

Returns the number of quick, consecutive
clicks the user has made (including this
event). For example, returns 2 for a double
click.

int getButton()

int getX()
int getY()

Returns which mouse button, if any, has a
changed state. One of the following
constants is returned: NOBUTTON,
BUTTON1, BUTTON2, or BUTTON3.
Return the (x,y) position at which the event
occurred, relative to the component that
fired the event.

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
MouseAdapter Class
• MouseAdapter class provides an empty implementation of all the
methods in MouseListener interface. This class exists as convenience
for creating listener objects.
• Extend this class to create a MouseEvent listener and override the
methods for the events of interest.
• Create a listener object using the extended class and then register it
with a component using the component's addMouseListener method.
• When a mouse button is pressed, released, or clicked (pressed and
released), or when the mouse cursor enters or exits the component,
the relevant method in the listener object is invoked and the
MouseEvent is passed to it.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
MouseMotionListener Interface
• Mouse-motion events notify when the user uses the mouse (or a
similar input device) to move the onscreen cursor.
• If an application requires the detection of both mouse events and
mouse-motion events, use the MouseInputAdapter class.
• It implements the MouseInputListener a convenient interface that
implements both the MouseListener and MouseMotionListener
interfaces.

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Methods of MouseMotionListener Interface
Method

mouseDragged(MouseEvent)

mouseMoved(MouseEvent)

Purpose
Called in response to the user moving
the mouse while holding a mouse
button down. This event is fired by the
component that fired the most recent
mouse-pressed event, even if the
cursor is no longer over that
component.
Called in response to the user moving
the mouse with no mouse buttons
pressed. This event is fired by the
component that's currently under the
cursor.

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
WindowListener Interface
• The listener interface for receiving window events.
• The class that is interested in processing a window event either
implements this interface (and all the methods it contains) or
extends the abstract WindowAdapter class (overriding only the
methods of interest).
• The listener object created from that class is then registered
with a Window using the window's addWindowListener ()
method.

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Methods of WindowListener
Method

Purpose

void windowClosing
(WindowEvent e)

Invoked when the user attempts to close the
window from the window's system menu.

void windowOpened
(WindowEvent e)

Invoked the first time a window is made visible.

void windowClosed
(WindowEvent e)

Invoked when a window has been closed as the
result of calling dispose on the window.

void windowIconified
(WindowEvent e)

Invoked when a window is changed from a
normal to a minimized state.

void windowDeiconified(W Invoked when a window is changed from a
indowEvent e)
minimized to a normal state.
void windowActivated
(WindowEvent e)

Invoked when the Window is set to be the active
Window.

void windowDeactivated(W Invoked when a Window is no longer the active
indowEvent e)
Window.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Event handling

More Related Content

What's hot

Java awt tutorial javatpoint
Java awt tutorial   javatpointJava awt tutorial   javatpoint
Java awt tutorial javatpointRicardo Garcia
 
JAVA GUI PART III
JAVA GUI PART IIIJAVA GUI PART III
JAVA GUI PART IIIOXUS 20
 
Advance Java Programming (CM5I) 2.Swing
Advance Java Programming (CM5I) 2.SwingAdvance Java Programming (CM5I) 2.Swing
Advance Java Programming (CM5I) 2.SwingPayal Dungarwal
 
Swing and AWT in java
Swing and AWT in javaSwing and AWT in java
Swing and AWT in javaAdil Mehmoood
 
Dr. Rajeshree Khande :Introduction to Java AWT
Dr. Rajeshree Khande :Introduction to Java AWTDr. Rajeshree Khande :Introduction to Java AWT
Dr. Rajeshree Khande :Introduction to Java AWTDrRajeshreeKhande
 
Complete java swing
Complete java swingComplete java swing
Complete java swingjehan1987
 
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
 
GUI Programming in JAVA (Using Netbeans) - A Review
GUI Programming in JAVA (Using Netbeans) -  A ReviewGUI Programming in JAVA (Using Netbeans) -  A Review
GUI Programming in JAVA (Using Netbeans) - A ReviewFernando Torres
 
The AWT and Swing
The AWT and SwingThe AWT and Swing
The AWT and Swingadil raja
 

What's hot (20)

Awt
AwtAwt
Awt
 
tL19 awt
tL19 awttL19 awt
tL19 awt
 
Gui programming (awt)
Gui programming (awt)Gui programming (awt)
Gui programming (awt)
 
Java awt tutorial javatpoint
Java awt tutorial   javatpointJava awt tutorial   javatpoint
Java awt tutorial javatpoint
 
Gui
GuiGui
Gui
 
JAVA GUI PART III
JAVA GUI PART IIIJAVA GUI PART III
JAVA GUI PART III
 
Advance Java Programming (CM5I) 2.Swing
Advance Java Programming (CM5I) 2.SwingAdvance Java Programming (CM5I) 2.Swing
Advance Java Programming (CM5I) 2.Swing
 
Java swing
Java swingJava swing
Java swing
 
Swing and AWT in java
Swing and AWT in javaSwing and AWT in java
Swing and AWT in java
 
Dr. Rajeshree Khande :Introduction to Java AWT
Dr. Rajeshree Khande :Introduction to Java AWTDr. Rajeshree Khande :Introduction to Java AWT
Dr. Rajeshree Khande :Introduction to Java AWT
 
GUI Programming with Java
GUI Programming with JavaGUI Programming with Java
GUI Programming with Java
 
Swing
SwingSwing
Swing
 
Awt and swing in java
Awt and swing in javaAwt and swing in java
Awt and swing in java
 
Complete java swing
Complete java swingComplete java swing
Complete java swing
 
Chapter 1 swings
Chapter 1 swingsChapter 1 swings
Chapter 1 swings
 
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)
 
GUI Programming in JAVA (Using Netbeans) - A Review
GUI Programming in JAVA (Using Netbeans) -  A ReviewGUI Programming in JAVA (Using Netbeans) -  A Review
GUI Programming in JAVA (Using Netbeans) - A Review
 
java swing
java swingjava swing
java swing
 
The AWT and Swing
The AWT and SwingThe AWT and Swing
The AWT and Swing
 
Awt controls ppt
Awt controls pptAwt controls ppt
Awt controls ppt
 

Viewers also liked (16)

List classes
List classesList classes
List classes
 
Questions for Class I & II
Questions for Class I & IIQuestions for Class I & II
Questions for Class I & II
 
Jdbc
JdbcJdbc
Jdbc
 
Multi threading
Multi threadingMulti threading
Multi threading
 
Servlets
ServletsServlets
Servlets
 
Internationalization
InternationalizationInternationalization
Internationalization
 
Basic IO
Basic IOBasic IO
Basic IO
 
Distributed Programming (RMI)
Distributed Programming (RMI)Distributed Programming (RMI)
Distributed Programming (RMI)
 
Swing api
Swing apiSwing api
Swing api
 
Networking
NetworkingNetworking
Networking
 
Sms several papers
Sms several papersSms several papers
Sms several papers
 
Jun 2012(1)
Jun 2012(1)Jun 2012(1)
Jun 2012(1)
 
Collection framework
Collection frameworkCollection framework
Collection framework
 
Packages
PackagesPackages
Packages
 
Classes and Nested Classes in Java
Classes and Nested Classes in JavaClasses and Nested Classes in Java
Classes and Nested Classes in Java
 
Generics
GenericsGenerics
Generics
 

Similar to Event handling

Similar to Event handling (20)

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
 
event-handling.pptx
event-handling.pptxevent-handling.pptx
event-handling.pptx
 
tL20 event handling
tL20 event handlingtL20 event handling
tL20 event handling
 
Event handling
Event handlingEvent handling
Event handling
 
OOP Lecture 11-EventHandling1.pptx
OOP Lecture 11-EventHandling1.pptxOOP Lecture 11-EventHandling1.pptx
OOP Lecture 11-EventHandling1.pptx
 
Event Handling in JAVA
Event Handling in JAVAEvent Handling in JAVA
Event Handling in JAVA
 
File Handling
File HandlingFile Handling
File Handling
 
What is Event
What is EventWhat is Event
What is Event
 
Event handling62
Event handling62Event handling62
Event handling62
 
PROGRAMMING IN JAVA- unit 4-part II
PROGRAMMING IN JAVA- unit 4-part IIPROGRAMMING IN JAVA- unit 4-part II
PROGRAMMING IN JAVA- unit 4-part II
 
B2. activity and intent
B2. activity and intentB2. activity and intent
B2. activity and intent
 
Ajp notes-chapter-03
Ajp notes-chapter-03Ajp notes-chapter-03
Ajp notes-chapter-03
 
Event handling in Java(part 1)
Event handling in Java(part 1)Event handling in Java(part 1)
Event handling in Java(part 1)
 
ITE 1122_ Event Handling.pptx
ITE 1122_ Event Handling.pptxITE 1122_ Event Handling.pptx
ITE 1122_ Event Handling.pptx
 
Chap - 2 - Event Handling.pptx
Chap - 2 - Event Handling.pptxChap - 2 - Event Handling.pptx
Chap - 2 - Event Handling.pptx
 
Events1
Events1Events1
Events1
 
Lecture 18
Lecture 18Lecture 18
Lecture 18
 
Event+driven+programming key+features
Event+driven+programming key+featuresEvent+driven+programming key+features
Event+driven+programming key+features
 
EventHandling.pptx
EventHandling.pptxEventHandling.pptx
EventHandling.pptx
 
CS3391 -OOP -UNIT – V NOTES FINAL.pdf
CS3391 -OOP -UNIT – V NOTES FINAL.pdfCS3391 -OOP -UNIT – V NOTES FINAL.pdf
CS3391 -OOP -UNIT – V NOTES FINAL.pdf
 

More from Ravi Kant Sahu

String handling(string buffer class)
String handling(string buffer class)String handling(string buffer class)
String handling(string buffer class)Ravi Kant Sahu
 
String handling(string class)
String handling(string class)String handling(string class)
String handling(string class)Ravi Kant Sahu
 
Introduction to Java Programming
Introduction to Java ProgrammingIntroduction to Java Programming
Introduction to Java ProgrammingRavi Kant Sahu
 

More from Ravi Kant Sahu (6)

Java beans
Java beansJava beans
Java beans
 
Applets
AppletsApplets
Applets
 
Exception handling
Exception handlingException handling
Exception handling
 
String handling(string buffer class)
String handling(string buffer class)String handling(string buffer class)
String handling(string buffer class)
 
String handling(string class)
String handling(string class)String handling(string class)
String handling(string class)
 
Introduction to Java Programming
Introduction to Java ProgrammingIntroduction to Java Programming
Introduction to Java Programming
 

Recently uploaded

Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Hyundai Motor Group
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 

Recently uploaded (20)

Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 

Event handling

  • 1. Programming in Java Event Handling By Ravi Kant Sahu Asst. Professor Lovely Professional University, Punjab
  • 3. Introduction • An event can be defined as a signal to the program that something has happened. • Events are triggered either by external user actions, such as mouse movements, button clicks, and keystrokes, or by internal program activities, such as a timer. • The program can choose to respond to or ignore an event. • The component that creates an event and fires it is called the source object or source component. • For example, a button is the source object for a button-clicking action event. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 4. Introduction • An event is an instance of an event class. • The root class of the event classes is java.util.EventObject. • We can identify the source object of an event using the getSource() method in the EventObject class. • The subclasses of EventObject deal with special types of events, such as action events, window events, component events, mouse events, and key events. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 5. Delegation event MoDel Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 6. The Delegation Event Model • The delegation event model defines standard and consistent mechanisms to generate and process events. Principle: • A source generates an event and sends it to one or more listeners. • The listener waits until it receives an event. • Once an event is received, the listener processes the event and then returns. Advantage: • 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. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 7. • 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. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 8. Event • 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. • For Example, pressing a button, entering a character via the keyboard, selecting an item in a list, and clicking the mouse. • Events may also occur that are not directly caused by interactions with a user interface. • For example, an event may be generated when a timer expires, a counter exceeds a value, a software or hardware failure occurs, or an operation is completed. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 9. Event Source • An Event 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. public void addTypeListener(TypeListener el) Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 10. • When an event occurs, all registered listeners are notified and receive a copy of the event object. This is known as multicasting the event. • In all cases, notifications are sent only to listeners that register to receive them. • Some sources may allow only one listener to register. public void addTypeListener(TypeListener el) throws java.util.TooManyListenersException Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 11. Event Listener • 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. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 12. Listener interfaces Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 13. Listener API Table Listener Interface Listener Methods ActionListener actionPerformed(ActionEvent) ItemListener itemStateChanged(ItemEvent) MouseListener mouseClicked(MouseEvent) mouseEntered(MouseEvent) mouseExited(MouseEvent) mousePressed(MouseEvent) mouseReleased(MouseEvent) MouseMotionListener KeyListener mouseDragged(MouseEvent) mouseMoved(MouseEvent) keyPressed(KeyEvent) keyReleased(KeyEvent) keyTyped(KeyEvent) Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 14. ActionListener • Action listeners are most common event handlers to implement. • An action event occurs, whenever an action is performed by the user. • We implement an action listener to define what should be done when an user performs certain operation. Examples: When the user clicks a button, chooses a menu item, presses Enter in a text field. • The result is that an actionPerformed message is sent to all action listeners that are registered on the relevant component. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 15. • To write an Action Listener, follow the steps given below: • Declare an event handler class and specify that the class either implements an ActionListener interface or extends a class that implements an ActionListener interface. For example: public class MyClass implements ActionListener { • Register an instance of the event handler class as a listener on one or more components. For example: someComponent.addActionListener(instanceOfMyClass); • Include code that implements the methods in listener interface. For example: public void actionPerformed(ActionEvent e) { ...//code that reacts to the action... } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 16. ActionEvent Class Method Purpose String getActionCommand() Returns the string associated with this action. Most objects that can fire action events support a method called setActionCommand that lets you set this string. Object getSource() Returns the object that fired the event. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 17. ItemListener Interface • Item events are fired by components that implement the ItemSelectable interface. • Generally, ItemSelectable components maintain on/off state for one or more items. • The Swing components that fire item events include buttons like check boxes, check menu items, toggle buttons and combo boxes etc. • ItemListener Interface has only one method. public void itemStateChanged (ItemEvent) Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 18. ItemEvent class Method Object getItem() Purpose Returns the component-specific object associated with the item whose state changed. Often this is a String containing the text on the selected item. ItemSelectable getItemSelectable() Returns the component that fired the item event. You can use this instead of the getSource method. int getStateChange() Returns the new state of the item. The ItemEvent class defines two states: SELECTED and DESELECTED. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 19. KeyListener Interface • Key events indicate when the user is typing at the keyboard. • Key events are fired by the component with the keyboard focus when the user presses or releases keyboard keys. • Notifications are sent about two basic kinds of key events: – The typing of a Unicode character – The pressing or releasing of a key on the keyboard Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 20. • The first kind of event is called a key-typed event. • To know when the user types a Unicode character ? whether by pressing one key such as 'a' or by pressing several keys in sequence ? • The second kind is either a key-pressed or key-released event. • To know when the user presses the F1 key, or whether the user pressed the '3' key on the number pad, you handle key-pressed events. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 21. Methods of KeyListener Interface Method Purpose keyTyped(KeyEvent) Called just after the user types a Unicode character into the listenedto component. keyPressed(KeyEvent) Called just after the user presses a key while the listened-to component has the focus. keyReleased(KeyEvent) Called just after the user releases a key while the listened-to component has the focus. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 22. KeyEvent class Method int getKeyChar() Purpose Obtains the Unicode character associated with this event. int getKeyCode() Obtains the key code associated with this event. The key code identifies the particular key on the keyboard that the user pressed or released. For example, VK_A specifies the key labeled A, and VK_ESCAPE specifies the Escape key. boolean isActionKey() Returns true if the key firing the event is an action key. Examples of action keys include Page Up, Caps Lock, the arrow and function keys. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 23. MouseListener Interface • Mouse events notify when the user uses the mouse (or similar input device) to interact with a component. • Mouse events occur when the cursor enters or exits a component's onscreen area and when the user presses or releases one of the mouse buttons. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 24. Methods of MouseListener Interface Method Purpose mouseClicked(MouseEvent) Called just after the user clicks the listened-to component. mouseEntered(MouseEvent) Called just after the cursor enters the bounds of the listened-to component. mouseExited(MouseEvent) Called just after the cursor exits the bounds of the listened-to component. mousePressed(MouseEvent) Called just after the user presses a mouse button while the cursor is over the listened-to component. mouseReleased(MouseEvent) Called just after the user releases a mouse button after a mouse press over the listened-to component. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 25. MouseEvent class Method Purpose int getClickCount() Returns the number of quick, consecutive clicks the user has made (including this event). For example, returns 2 for a double click. int getButton() int getX() int getY() Returns which mouse button, if any, has a changed state. One of the following constants is returned: NOBUTTON, BUTTON1, BUTTON2, or BUTTON3. Return the (x,y) position at which the event occurred, relative to the component that fired the event. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 26. MouseAdapter Class • MouseAdapter class provides an empty implementation of all the methods in MouseListener interface. This class exists as convenience for creating listener objects. • Extend this class to create a MouseEvent listener and override the methods for the events of interest. • Create a listener object using the extended class and then register it with a component using the component's addMouseListener method. • When a mouse button is pressed, released, or clicked (pressed and released), or when the mouse cursor enters or exits the component, the relevant method in the listener object is invoked and the MouseEvent is passed to it. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 27. MouseMotionListener Interface • Mouse-motion events notify when the user uses the mouse (or a similar input device) to move the onscreen cursor. • If an application requires the detection of both mouse events and mouse-motion events, use the MouseInputAdapter class. • It implements the MouseInputListener a convenient interface that implements both the MouseListener and MouseMotionListener interfaces. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 28. Methods of MouseMotionListener Interface Method mouseDragged(MouseEvent) mouseMoved(MouseEvent) Purpose Called in response to the user moving the mouse while holding a mouse button down. This event is fired by the component that fired the most recent mouse-pressed event, even if the cursor is no longer over that component. Called in response to the user moving the mouse with no mouse buttons pressed. This event is fired by the component that's currently under the cursor. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 29. WindowListener Interface • The listener interface for receiving window events. • The class that is interested in processing a window event either implements this interface (and all the methods it contains) or extends the abstract WindowAdapter class (overriding only the methods of interest). • The listener object created from that class is then registered with a Window using the window's addWindowListener () method. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 30. Methods of WindowListener Method Purpose void windowClosing (WindowEvent e) Invoked when the user attempts to close the window from the window's system menu. void windowOpened (WindowEvent e) Invoked the first time a window is made visible. void windowClosed (WindowEvent e) Invoked when a window has been closed as the result of calling dispose on the window. void windowIconified (WindowEvent e) Invoked when a window is changed from a normal to a minimized state. void windowDeiconified(W Invoked when a window is changed from a indowEvent e) minimized to a normal state. void windowActivated (WindowEvent e) Invoked when the Window is set to be the active Window. void windowDeactivated(W Invoked when a Window is no longer the active indowEvent e) Window. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)