Java Reference
In-Depth Information
When the
JButton
component is selected, all registered
ActionListener
objects are notified.
When the button is selected, an
ActionEvent
is passed to each listener. This event passes along
the
actionCommand
property of the button to help identify which button was selected when
a shared listener is used across multiple components. If the
actionCommand
property hasn't
been explicitly set, the current
text
property is passed along instead. The explicit use of the
actionCommand
property is helpful with localization. Because the
text
property of the
JButton
is
what the user sees, you as the handler of the button selection event listener cannot rely on a
localized text label for determining which button was selected. So, while the
text
property can
be localized so that a Yes button in English can say Sí in a Spanish version, if you explicitly set
the
actionCommand
to be the
"Yes"
string, then no matter which language the user is running in,
the
actionCommand
will remain
"Yes"
and not take on the localized
text
property setting.
Listing 4-7 adds the event-handling capabilities to the default button example in Listing 4-6
(see Figure 4-13). Notice that the default button behavior works properly: press Enter from any
component, and button 2 (the default) will be activated.
Listing 4-7.
Watching Button Selection Events
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ActionButtonSample {
public static void main(String args[]) {
Runnable runner = new Runnable() {
public void run() {
JFrame frame = new JFrame("DefaultButton");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
String command = actionEvent.getActionCommand();
System.out.println("Selected: " + command);
}
};
frame.setLayout(new GridLayout(2, 2, 10, 10));
JButton button1 = new JButton("Text Button");
button1.setMnemonic(KeyEvent.VK_B);
button1.setActionCommand("First");
button1.addActionListener(actionListener);
frame.add(button1);