Java Reference
In-Depth Information
B.3.3 events
When the user types on the keyboard or uses the mouse, the operating system pro-
duces an event. Java's original event-handling system was cumbersome and has
been completely redone. The new model, in place since Java 1.1, is much simpler
to program than the old. Note that the two models are incompatible: Java 1.1
events are not understood by Java 1.0 compilers. The basic rules are as follows:
Java's original
event-handling sys-
tem was cumber-
some and has been
completely redone.
1.
Any class that is willing to provide code to handle an event
must implement a listener interface. Examples of listener inter-
faces are ActionListener , WindowListener , and MouseListener . As
usual, implementing an interface means that all methods of the
interface must be defined by the class.
2.
An object that is willing to handle the event generated by a
component must register its willingness with an addListener
message sent to the event-generating component. When a com-
ponent generates an event, the event will be sent to the object
that has registered to receive it. If no object has registered to
receive it, then it is ignored.
For an example, consider the action event, which is generated when the
user presses a JButton , hits Return while in a JTextField , or selects from a
JList or JMenuItem . The simplest way to handle the JButton click is to have its
container implement ActionListener by providing an actionPerformed method
and registering itself with the JButton as its event handler.
This is shown for our running example in Figure B.1 as follows. Recall
that in Figure B.3, we already have done two things. At line 5, GUI declares
that it implements the ActionListener , and at line 11, an instance of GUI reg-
isters itself as its JButton 's action event handler. In Figure B.9, we imple-
ment the listener by having actionPerformed call setParam in the GUICanvas
class. This example is simplified by the fact that there is only one JButton , so
when actionPerformed is called, we know what to do. If GUI contained several
JButton s and it registered to receive events from all of these JButton s, then
actionPerformed would have to examine the evt parameter to determine
which JButton event was to be processed: This might involve a sequence of
if / else tests. 4 The evt parameter, which in this case is an ActionEvent refer-
ence, is always passed to an event handler. The event will be specific to the
type of handler ( ActionEvent , WindowEvent , and so on), but it will always be a
subclass of AWTEvent .
An action event is
generated when
the user presses a
JButton ; it is han-
dled by an
actionListener .
4. One way to do this is to use evt.getSource( ) , which returns a reference to the object that
generated the event.
 
 
Search WWH ::




Custom Search