Java Reference
In-Depth Information
getActionCommand() method to look at individual keywords associated with
the menu items. You will then use the getSource() method to look for which of
the individual buttons was clicked.
Searching for the Exit and Clear Commands
Figure 6-22 displays the code used to search the menu items for a click.
During program execution, the ActionCommand of any click in the interface,
menu, or button will be stored in the variable arg. Line 135 assigns the returned
value from the getActionCommand() method to a String variable named arg.
Then, if statements compare arg to the assigned keywords. Because there are
only five menu options, comparing each sequentially does not require an unrea-
sonable amount of code. Had there been many more options, constructing an
array would be a more efficient way to identify which menu item the user
clicked.
132
public void actionPerformed ( ActionEvent e )
133
{
134
// test for menu item clicks
135
String arg = e.getActionCommand () ;
136
if ( arg == "Exit" )
137
System .exit ( 0 ) ;
138
139
if ( arg == "Clear" )
140
{
141
clearText = true ;
142
first = true ;
143
op1 = 0.0;
144
lcd.setText ( "" ) ;
145
lcd.requestFocus () ;
146
}
147
FIGURE 6-22
As noted above, the ActionCommand of any click in the interface, menu, or
button is stored in the variable arg. Line 136 compares the variable, arg, with the
keyword, Exit. If a match is found, it means that the user clicked the Exit com-
mand on the File menu. The System.exit(0) method is called and the program
terminates.
Line 139 compares the variable, arg, with the keyword, Clear. If a match is
found, the user has clicked the Clear command on the Exit menu. Lines 141 and
142 then set the boolean flags, clearText and first, back to true, and Line 143 sets
the double value, op1, to 0.0 so that the user can begin a new calculation. In line
144, the TextField is set to a null String ("") and the focus is returned to the lcd
TextField in line 145.
The following step enters the code to search for clicks of the Exit and Clear
commands.
Search WWH ::




Custom Search