Prior to this discussion, we looked at Java classes and objects and at methods to manipulate an object's variables. We have also looked briefly at several interface components, such as buttons and panels. However, we have not considered how to make anything happen. That is, how to make a button do something or how to start the flow of messages among objects. The key to making a Java program do something lies in events.
Many programs, after they are started and initialized, go into a wait state waiting for something to happen. One important set of somethings is user interface actions: the user selects a menu option, clicks on a window with the mouse, types something on the keyboard, etc. At a very deep level of the system, these actions are observed and paramaterized, and their symbolic representations are passed up through several layers until they arrive at the application program. In Java, these actions emerge as one of several different kinds of events.
Events emerge from the operating system and the Java Virtual Machine in several different Java components, such as a
Button
or aPanel
. Thus, when a user "presses" a particular button shown on the screen, such as a "clear" button, the corresponding Java object receives an action event indicating that fact. Similarly, when the mouse is clicked or moved within a particular panel, that object receives the corresponding mouseEvent.The event can be processed within the component, if that suits the programmers purpose. but it may also be forwarded to some other object for processing, if that is more convenient, as is often the case. For example, consider a program that provides a whiteboard drawing area (panel) on which the user can draw with the mouse and a clear button that will erase the drawing. It will probably be more convenient to process the clear action in the panel object, where methods can be invoked directly to paint the panel white or some other background color, rather than to do that from within the button object.
The mechanism that allows this to be done is called notification. Java provides a mechanism whereby the object that would like to be notified when a particular class of events occurs in a second object to register with that object. Thereafter, when such events arrive in the object, they are forwarded to the "interested" object for processing.
Graphically, this process looks like the following:
Java Action - Listener Model. Actions performed by UI devices sent to corresponding Java objects. Other objects interested in those events register with the receiving objects and are then notified when any such events are received.