SlideShare una empresa de Scribd logo
1 de 31
Programming in Java
Event Handling
Outlines
• Delegation Event Model
• ActionListener
• ItemListener
• KeyListener
• MouseListener
• MouseMotionListener
• WindowListener
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.
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.
Delegation Event Model
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.
• 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.
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.
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)
• 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
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.
Listener Interfaces
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 mouseDragged(MouseEvent)
mouseMoved(MouseEvent)
KeyListener
keyPressed(KeyEvent)
keyReleased(KeyEvent)
keyTyped(KeyEvent)
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.
• 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... }
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.
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)
ItemEvent class
Method Purpose
Object getItem() 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.
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
• 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.
Methods of KeyListener Interface
Method Purpose
keyTyped(KeyEvent) Called just after the user types a
Unicode character into the listened-
to 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.
KeyEvent class
Method Purpose
char getKeyChar()
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.
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.
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.
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()
Returns which mouse button, if any, has a
changed state. One of the following
constants is returned: NOBUTTON,
BUTTON1, BUTTON2, or BUTTON3.
int getX()
int getY()
Return the (x,y) position at which the event
occurred, relative to the component that
fired the event.
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.
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.
Methods of MouseMotionListener Interface
Method Purpose
mouseDragged(MouseEvent)
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.
mouseMoved(MouseEvent)
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.
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.
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
indowEvent e)
Invoked when a window is changed from a
minimized to a normal state.
void windowActivated
(WindowEvent e)
Invoked when the Window is set to be the active
Window.
void windowDeactivated(
WindowEvent e)
Invoked when a Window is no longer the active
Window.
tL20 event handling

Más contenido relacionado

La actualidad más candente

Android notification
Android notificationAndroid notification
Android notification
Krazy Koder
 

La actualidad más candente (20)

Java Collections
Java  Collections Java  Collections
Java Collections
 
Remote Method Invocation in JAVA
Remote Method Invocation in JAVARemote Method Invocation in JAVA
Remote Method Invocation in JAVA
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
History of java'
History of java'History of java'
History of java'
 
Java I/O
Java I/OJava I/O
Java I/O
 
Client-Server Computing
Client-Server ComputingClient-Server Computing
Client-Server Computing
 
6. static keyword
6. static keyword6. static keyword
6. static keyword
 
I/O Streams
I/O StreamsI/O Streams
I/O Streams
 
Android notification
Android notificationAndroid notification
Android notification
 
Chapter 1 swings
Chapter 1 swingsChapter 1 swings
Chapter 1 swings
 
Java Swing JFC
Java Swing JFCJava Swing JFC
Java Swing JFC
 
Security auditing architecture
Security auditing architectureSecurity auditing architecture
Security auditing architecture
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
 
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
 
Asp.net state management
Asp.net state managementAsp.net state management
Asp.net state management
 
Java Streams
Java StreamsJava Streams
Java Streams
 
Java swing
Java swingJava swing
Java swing
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
 
Java awt
Java awtJava awt
Java awt
 

Destacado (10)

Java Event Handling
Java Event HandlingJava Event Handling
Java Event Handling
 
Event Handling in Java
Event Handling in JavaEvent Handling in Java
Event Handling in Java
 
Java programming-Event Handling
Java programming-Event HandlingJava programming-Event Handling
Java programming-Event Handling
 
Event handling
Event handlingEvent handling
Event handling
 
Java session11
Java session11Java session11
Java session11
 
Java lab-manual
Java lab-manualJava lab-manual
Java lab-manual
 
Java lab 2
Java lab 2Java lab 2
Java lab 2
 
Java Lab Manual
Java Lab ManualJava Lab Manual
Java Lab Manual
 
66781291 java-lab-manual
66781291 java-lab-manual66781291 java-lab-manual
66781291 java-lab-manual
 
Awt
AwtAwt
Awt
 

Similar a tL20 event handling

Similar a tL20 event handling (20)

Event Handling in JAVA
Event Handling in JAVAEvent Handling in JAVA
Event Handling in JAVA
 
Module 5.pptx
Module 5.pptxModule 5.pptx
Module 5.pptx
 
What is Event
What is EventWhat is Event
What is Event
 
Ajp notes-chapter-03
Ajp notes-chapter-03Ajp notes-chapter-03
Ajp notes-chapter-03
 
event-handling.pptx
event-handling.pptxevent-handling.pptx
event-handling.pptx
 
Module3.11.pptx
Module3.11.pptxModule3.11.pptx
Module3.11.pptx
 
Events1
Events1Events1
Events1
 
File Handling
File HandlingFile Handling
File Handling
 
Unit 6 Java
Unit 6 JavaUnit 6 Java
Unit 6 Java
 
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
Event handlingEvent handling
Event handling
 
Event handling
Event handlingEvent handling
Event handling
 
Event handling
Event handlingEvent handling
Event handling
 
AJP key event class.pptx
AJP key event class.pptxAJP key event class.pptx
AJP key event class.pptx
 
09events
09events09events
09events
 
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)
 
Chap - 2 - Event Handling.pptx
Chap - 2 - Event Handling.pptxChap - 2 - Event Handling.pptx
Chap - 2 - Event Handling.pptx
 
Unit-3 event handling
Unit-3 event handlingUnit-3 event handling
Unit-3 event handling
 
Java gui event
Java gui eventJava gui event
Java gui event
 
event_handling.ppt
event_handling.pptevent_handling.ppt
event_handling.ppt
 

Más de teach4uin (20)

Controls
ControlsControls
Controls
 
validation
validationvalidation
validation
 
validation
validationvalidation
validation
 
Master pages
Master pagesMaster pages
Master pages
 
.Net framework
.Net framework.Net framework
.Net framework
 
Scripting languages
Scripting languagesScripting languages
Scripting languages
 
Css1
Css1Css1
Css1
 
Code model
Code modelCode model
Code model
 
Asp db
Asp dbAsp db
Asp db
 
State management
State managementState management
State management
 
security configuration
security configurationsecurity configuration
security configuration
 
static dynamic html tags
 static dynamic html tags static dynamic html tags
static dynamic html tags
 
static dynamic html tags
static dynamic html tagsstatic dynamic html tags
static dynamic html tags
 
New microsoft office power point presentation
New microsoft office power point presentationNew microsoft office power point presentation
New microsoft office power point presentation
 
.Net overview
.Net overview.Net overview
.Net overview
 
Stdlib functions lesson
Stdlib functions lessonStdlib functions lesson
Stdlib functions lesson
 
enums
enumsenums
enums
 
memory
memorymemory
memory
 
array
arrayarray
array
 
storage clas
storage classtorage clas
storage clas
 

Último

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Último (20)

AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 

tL20 event handling

  • 2. Outlines • Delegation Event Model • ActionListener • ItemListener • KeyListener • MouseListener • MouseMotionListener • WindowListener
  • 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.
  • 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.
  • 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.
  • 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.
  • 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.
  • 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)
  • 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
  • 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.
  • 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 mouseDragged(MouseEvent) mouseMoved(MouseEvent) KeyListener keyPressed(KeyEvent) keyReleased(KeyEvent) keyTyped(KeyEvent)
  • 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.
  • 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... }
  • 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.
  • 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)
  • 18. ItemEvent class Method Purpose Object getItem() 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.
  • 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
  • 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.
  • 21. Methods of KeyListener Interface Method Purpose keyTyped(KeyEvent) Called just after the user types a Unicode character into the listened- to 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.
  • 22. KeyEvent class Method Purpose char getKeyChar() 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.
  • 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.
  • 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.
  • 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() Returns which mouse button, if any, has a changed state. One of the following constants is returned: NOBUTTON, BUTTON1, BUTTON2, or BUTTON3. int getX() int getY() Return the (x,y) position at which the event occurred, relative to the component that fired the event.
  • 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.
  • 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.
  • 28. Methods of MouseMotionListener Interface Method Purpose mouseDragged(MouseEvent) 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. mouseMoved(MouseEvent) 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.
  • 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.
  • 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 indowEvent e) Invoked when a window is changed from a minimized to a normal state. void windowActivated (WindowEvent e) Invoked when the Window is set to be the active Window. void windowDeactivated( WindowEvent e) Invoked when a Window is no longer the active Window.