Java Reference
In-Depth Information
Line 39 uses a Button method called the addActionListener() method. Recall
that the ActionListener, which was implemented in the class header, is a listener
interface that listens for events. If an application is expected to perform some
action based on an event from a specific component, such as a Button, the code
must (1) implement ActionListener, as it did in line 14 in the class header, and
(2) register ActionListener to receive events from the Button, by calling the
component's addActionListener() method.
Each component has an addActionListener() method that registers, or
assigns, an ActionListener to receive action events from that component. In the
Body Mass Index Calculator applet, the addActionListener() method for a
Button is used to associate the specific Button component, calcButton, with
ActionListener. When a user clicks the calcButton, the calcButton sends an action
event to ActionListener.
As shown in line 39 of Figure 3-41, the addActionListener() method has
only one argument, which is used to assign the specific instance of the
Button class that will send action events to the ActionListener. In line 39, the
addActionListener() method uses the keyword, this, as the argument for the
method. The keyword, this, refers back to the component itself — in this case,
the calcButton instance of the Button class. The calcButton thus is the object
monitored by the listener interface, ActionListener. In summary, you can think of
the ActionListener as telling the applet to listen for the click on the calcButton,
and the keyword, this, as identifying which click event code to execute after the
user clicks the calcButton.
In line 41, the image for the applet is retrieved from storage and placed in
the applet. As in Chapter 2, the getImage() method is used to load an image
into an applet. The getImage() method calls a second method called the
getDocumentBase() method, which allows the applet to pull the image from
the current folder in which your applet class is stored. The getImage() method
creates and returns the image object to the variable, logo, which represents the
loaded image.
The step on the next page codes the init() method, which adds the
components to the applet window, sets the addActionListener() method for the
button, and gets the image to display in the applet window.
Search WWH ::




Custom Search