Académique Documents
Professionnel Documents
Culture Documents
Event Handling
Outlines
The component that creates an event and fires it is called the source
object or source component.
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.
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.
First, it must have been registered with one or more sources to receive
notifications about specific types of events.
The methods that receive and process events are defined in a set of
interfaces found in java.awt.event.
ItemListener itemStateChanged(ItemEvent)
mouseClicked(MouseEvent)
mouseEntered(MouseEvent)
MouseListener mouseExited(MouseEvent)
mousePressed(MouseEvent)
mouseReleased(MouseEvent)
MouseMotionListener mouseDragged(MouseEvent)
mouseMoved(MouseEvent)
keyPressed(KeyEvent)
KeyListener keyReleased(KeyEvent)
keyTyped(KeyEvent)
ActionListener
Action listeners are most common event handlers to implement.
The Swing components that fire item events include buttons like
check boxes, check menu items, toggle buttons and combo boxes etc.
Key events are fired by the component with the keyboard focus
when the user presses or releases keyboard keys.
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
Create a listener object using the extended class and then register it
with a component using the component's addMouseListener method.
Method Purpose