|
|
|
Events
Similar to an exception, an event is a (hardware) condition that is signaled.
Unlike an exception, an event is a normal, expected condition.
Common events are from input devices, such as
- mouse events - mouse up, mouse down, mouse move
- keyboard events - key up, key down
- network events - packet arrival
- window events - window resized, window dragged, focus lost
Special hardware detects and signals these events.
Each event has additional information.
For example a mouse movement event has an x and y coordinate.
In a Graphical User Interface (GUI), there exist widgets which
are high-level events constructed from low-level events in specific areas.
- button down - mouse down, mouse up in a particular screen area
- check-box - mouse down, mouse up in a rectangular area
- radio-box - mouse down, mouse up in a rectangular area
- text-area - keyboard events in a scrolling text field
There is special hardware support for graphics.
At a higher-language level, operations (typically function calls or
methods on a graphics object) are provided.
In a language that supports exception handlers, flow-of-control switches
to the handlers when an exception is raised, and the the normal flow-of-control
resumes.
In event-driven programming, there is essentially no normal flow-of-control!
Only the event (exception) handlers exist. Flow-of-control is entirely
driven by responding to events.
The event dispatcher is called the main loop.
while (TRUE) { // loop forever
while (empty(event.queue)); // wait for an event
event = pop(event.queue);
event.type(event.information);
}
// a mouseDown event handler
public boolean mouseDown(Event event, int int x, int y) {
// what to do on a mouse down
}
// a buttonDown event handler
buttonDown(button b) {
// what to do on a button down
}
Here is a Java example. Notice that the main event loop has
been completely eliminated. The action method controls the
dispatching of an event.
/** Respond to user actions on controls. */
public boolean action(Event e, Object arg) {
if (e.target instanceof TextField) {
setSliderValue(getValue());
controller.convert(this);
return true;
}
if (e.target instanceof Choice) {
controller.convert(this);
return true;
}
return false;
}
/** Respond to the slider. */
public boolean handleEvent(Event e) {
if (e.target instanceof Scrollbar) {
textField.setText(String.valueOf(slider.getValue()));
controller.convert(this);
}
return super.handleEvent(e);
}
Source of Information
These lecture notes are based on Chapter 14 in "Programming Languages, 6ed"
by Robert Sebesta.
|