Java Reference
In-Depth Information
setActionCommand and getActionCommand
Every button and every menu item has a string associated with it that is known as the
action command for that button or menu item. When the button or menu item is clicked, it
fires an action event e . The following invocation returns the action command for the button
or menu item that fired e :
e.getActionCommand( )
The method actionPerformed typically uses this action command string to decide which
button or menu item was clicked.
The default action command for a button or menu item is the string written on it, but
if you want, you can change the action command with an invocation of the method
setActionCommand . For example, the menu item chooseNext created by the following
code will display the string "Next" when it is a menu choice, but will have the string "Next
Menu Item" as its action command.
EXAMPLE
JMenuItem chooseNext = new JMenuItem("Next");
chooseNext.setActionCommand("Next Menu Item");
An alternate approach to defining action listeners is given in the next subsection.
That technique is, among other things, another way to deal with multiple buttons or
menu items that have the same thing written on them.
Listeners as Inner Classes
In all of our previous examples, our GUIs had only one action listener object to deal
with all action events from all buttons and menus in the GUI. The opposite extreme
also has much to recommend it. You can have a separate ActionListener class for
each button or menu item, so that each button or menu item has its own unique
action listener. There is then no need for a multiway if-else statement. The listener
knows which button or menu item was clicked because it listens to only one button or
menu item.
The approach outlined in the previous paragraph does have one down side: You
typically need to give a lot of definitions of ActionListener classes. Rather than
putting each of these classes in a separate file, it is much cleaner to make them private
inner classes. This has the added advantage of allowing the ActionListener classes to
have access to private instance variables and methods of the outer class.
In Display 17.16 , we re-created the GUI in Display 17.14 using the techniques of
this subsection.
 
Search WWH ::




Custom Search