Java Reference
In-Depth Information
In addition to the methods described, the getSource() method can be used on any event
object to determine which object generated the event.
Action Events
Action events occur when a user completes an action using components such as buttons,
check boxes, menu items, text fields, and radio buttons.
A class must implement the ActionListener interface to handle these events. In addi-
tion, the addActionListener() method must be called on each component that should
generate an action event—unless you want to ignore that component's action events.
The actionPerformed( ActionEvent ) method is the only method of the ActionListener
interface. It takes the following form:
public void actionPerformed(ActionEvent event) {
// ...
}
In addition to the getSource() method, you can use the getActionCommand() method on
the ActionEvent object to discover more information about the event's source.
By default, the action command is the text associated with the component, such as the
label on a button. You also can set a different action command for a component by call-
ing its setActionCommand( String ) method. The string argument should be the action
command's desired text.
For example, the following statements create a button and menu item and give both of
them the action command “Sort Files” :
12
JButton sort = new JButton(“Sort”);
JMenuItem menuSort = new JMenuItem(“Sort”);
sort.setActionCommand(“Sort Files”);
menuSort.setActionCommand(“Sort Files”);
Action commands are useful in a program in which more than one
component should cause the same thing to happen. By giving
both components the same action command, you can handle
them with the same code in an event-handling method.
NOTE
Search WWH ::




Custom Search