Java Reference
In-Depth Information
The actionPerformed() Method
The final set of code will create the event behind the Calculate button. Once
a user clicks the Calculate button and the click is received, a Java applet must
perform a task; in this case, it must calculate the Body Mass Index just as it did
in the previous two versions of the program.
When an object such as the calcButton causes an event to happen, the object
is called an event source . Each event source can have one or more listener inter-
faces, which become registered , or paired, with the event source at compile
time. In the Body Mass Index Calculator applet, the ActionListener interface is
registered with the calcButton using the addActionListener() method.
A listener interface has methods that specify what will happen when an
event is sent to the listener interface. These methods are called event handlers .
ActionListener has one event handler or method, called actionPerformed() ,
which is executed when the click event occurs. The actionPerformed() method
takes the general form shown in line 44 of Figure 3-43. It is common practice
to identify the ActionEvent parameter as e, although any variable name can
be used.
44
public void actionPerformed ( ActionEvent e )
45
{
46
47
inches = Integer .parseInt ( heightField.getText ()) ;
48
pounds = Integer .parseInt ( weightField.getText ()) ;
49
meters = inches / 39.36;
50
kilograms = pounds / 2.2;
51
index = kilograms / Math .pow ( meters,2 ) ;
52
outputLabel.setText ( "YOUR BODY MASS INDEX IS " + Math .round ( index ) + "." ) ;
53
}
54
FIGURE 3-43
In lines 47 and 48, the data entered by the user in the text box created by the
TextField component are retrieved using the getText() method. The getText()
method is used to retrieve text from a Label, TextField, or other AWT or Swing
component that uses text. Table 3-16 displays the general form of the
getText() method.
Table 3-16
getText() Method
General form:
object.getText():
Purpose:
To retrieve text from a Label, TextField, or other AWT or Swing
component that uses text. It returns a String composed of the
Label's caption or the user-supplied data from a TextField.
Examples:
1. heightField.getText();
2. myLabel.getText();
 
Search WWH ::




Custom Search