Java Reference
In-Depth Information
Event-Driven Programs
Your actions when you're using the GUI for a window-based program or an applet — clicking a menu item
or a button, moving the mouse, and so on — are first recognized by the operating system. For each action,
the operating system determines which of the programs currently running on your computer should know
about it and passes the action on to that program. When you click a mouse button, it's the operating system
that registers this and notes the position of the mouse cursor on the screen. It then decides which applica-
tion controls the window where the cursor was when you pressed the button and communicates the mouse
button-press to that program. The signals that a program receives from the operating system as a result of
your actions are called events . The basic idea of how actions and events are communicated to your program
code is illustrated in Figure 18-1 .
FIGURE 18-1
A program is not obliged to respond to any particular event. If you just move the mouse, for example, the
program need not invoke any code to react to that. If it doesn't, the event is quietly disposed of. Each event
that the program does recognize is associated with one or more methods, and when the event occurs — when
you click a menu item, for example — the appropriate methods are called automatically. A window-based
program is called an event-driven program because the sequence of events created as a result of your inter-
action with the GUI drives and determines what happens in the program.
NOTE Events are not limited to window-based applications — they are a quite general
concept. Mostprogramsthatcontrolormonitorthingsintherealworldareevent-driven. Any
occurrence external to a program, such as a switch closing or a preset temperature being
reached, can be registered as an event. In Java you can even create events within your pro-
gramtosignalsomeotherpartofthecodethatsomethingnoteworthyhashappened.However,
 
 
Search WWH ::




Custom Search