Java Reference
In-Depth Information
getActionCommand() versus getSource()
The getActionCommand() method is preferred over the
getSource() method for objects that can have multiple states,
such as menus and buttons.
Coding the actionPerformed() Method
In the Classics on DVD program, several objects may be clicked. Previously,
action Strings were assigned to each of the menu commands. Besides the menu
commands, a user also can click the JComboBox. On any of those occasions, the
program should perform the correct operation.
Figure 7-26 displays the code for the actionPerformed() event.
188
//event to process user clicks
189
public void actionPerformed ( ActionEvent e )
190
{
191
String arg = e.getActionCommand () ;
192
193
//user clicks the sort by combo box
194
if ( e.getSource () == fieldCombo )
195
{
196
switch ( fieldCombo.getSelectedIndex ())
197
{
198
case 0:
199
sort ( title ) ;
200
break ;
201
case 1:
202
sort ( studio ) ;
203
break ;
204
case 2:
205
sort ( year ) ;
206
break ;
207
}
208
}
209
210
//user clicks Exit on the File menu
211
if ( arg == "Exit" )
212
System .exit ( 0 ) ;
213
214
//user clicks Insert New DVD on the Edit menu
215
if ( arg == "Insert" )
216
{
217
//accept new data
218
String newTitle = JOptionPane.showInputDialog ( null ,
"Please enter the new movie's title" ) ;
219
String newStudio = JOptionPane.showInputDialog ( null ,
"Please enter the studio for " + newTitle ) ;
220
String newYear = JOptionPane.showInputDialog ( null ,
"Please enter the year for " + newTitle ) ;
221
222
//enlarge arrays
223
title = enlargeArray ( title ) ;
224
studio = enlargeArray ( studio ) ;
225
year = enlargeArray ( year ) ;
226
227
//add new data to arrays
228
title [ title.length-1 ] = newTitle;
229
studio [ studio.length-1 ] = newStudio;
230
year [ year.length-1 ] = newYear;
231
FIGURE 7-26
(continued)
Search WWH ::




Custom Search