At the moment we have displayed components, adding them to applications, and they work to the extent that you can press the buttons, select from the list etc., however they do not currently interact with your own code. If we want to use these components we must be aware of how the
java.awt.event package classes work. Note that with events the structure is quite different from Java 1.1.x (Java 1) to Java 1.2+.x (Java 2). There are many reasons for this, but the main reason is that there were serious problems with the event structure of Java 1, especially in relation to threaded applications. We are only examining the event structure of Java 2+.
ActionEvent object is generated by several of the components we have just discussed. A component such as a
Button object generates an
ActionEvent object when it is pressed. We also need to register a listener with the component so that we can direct the event to do something in our application. For a Button object we can do this using, for example:
Button b = new Button("Test Button");
this refers to an object that is capable of handling the
ActionEvent object that is passed to it. So in this case the class in which the
Button b is defined must implement that
ActionListener interface. So for a full example, use the following application:
Figure 6.16. Button Events Application
The application should display which button is pressed in the
TextField as soon as the button is pressed. The source code for this example is below.
Some notes about this code segment: