Java Reference
In-Depth Information
can be used with any
JButton
or
JMenuItem
to change the action command for that
component. Among other things, this will allow you to have different action com-
mands for two buttons, two menu items, or a button and menu item even though
they have the same string written on them.
The method
setActionCommand
takes a
String
argument that becomes the new action
command for the calling button or menu item. For example, consider the following code:
setAction-
Command
JButton nextButton =
new
JButton("Next");
nextButton.setActionCommand("Next Button");
JMenuItem chooseNext =
new
JMenuItem("Next");
chooseNext.setActionCommand("Next Menu Item");
If we had not used
setActionCommand
in the preceding code, then the button
nextButton
and the menu item
chooseNext
would both have the action command
"Next"
and so we
would have no way to tell which of the two components
nextButton
and
chooseNext
an
action event
"Next"
came from. However, using the method
setActionCommand
, we can
give them the different action commands
"Next
Button"
and
"Next
Menu
Item"
.
The action command for a
JButton
or
JMenuItem
is kept as the value of a private
instance variable for the
JButton
or
JMenuItem
. The method
setActionCommand
is
simply an ordinary mutator method that changes the value of this instance variable.
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
setAction-
Command
. 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.