Developer Data Modeling Mistakes: From Postgres to NoSQL
Event Handling Basics in Java
1. Event Handling
● How to capture events from the mouse and keyboard
● how to put together the most common components that
swing offers, along with a detailed coverage of the
events they generate.
2. Basics of Event Handling
● Any operating environment that supports GUIs
constantly monitors events such as key strokes or
mouse clicks. The operating environment reports these
events to the programs that are running. Program
decides what to do in response to these events.
● VB : event procedure (Limited)
● C : Constantly checks the event queue, go to any
length to hide the event queue from the programmer.
● Java takes an approach between VB and C.
3. Basics Cont ...
● Complete control from the event sources(such as buttons
or scrollbars) to event listeners.
● Any object can be event listener. In practice, we choose
an object that can conveniently carry out the desired
response to the object. This event delegation model gives
us much more flexibility.
● Event sources have methods that allow us to register
event listeners with them. When an event happens to the
source, the source sends a notification of that event to all
the listener objects that were registered for that event.
4. Basics Cont ...
● The information about the event is encapsulated in an
event object.
● Different event sources can produce different kinds of
events.
– Example : a button can send ActionEvent objects,
whereas a window can send WindowEvent objects.
6. Event handling in AWT
● A listener object is an instance of a class that implements
a special interface called a listener interface.
● An event source (e.g. button, menu, etc) is an object that
can register listener objects and send them event objects
(button click, menu selection, etc)
● The event source sends out event objects to all registered
listeners when that event occurs.
● The listener objects will then use the information in the
event object to determine their reaction to the event.
7. Event handling in AWT Cont...
● Register listener object with the source object by using the
following lines of code.
eventSourceObject.addEventListener(eventListenerObject);
● public class Beeper ... implements ActionListener {
...
//where initialization occurs:
button.addActionListener(this);
...
public void actionPerformed(ActionEvent e)
{ ...//Make a beep
sound...
}
8. A more complex Example
● Any number of event listener objects can listen for all
kinds of events from any number of event source
objects. For example, a program might create one
listener per event source. Or a program might have a
single listener for all events from all sources.
● Multiple listeners can register to be notified of events
of a particular type from a particular source. Also, the
same listener can listen to notifications from different
objects.