ActionCommand Example
This ActionCommand example puts two JButtons in a JFrame and acts on user selections. Importantly a setActionCommand() enables changes to be made to the names on the JButtons at some future date without necessitating changes to the ActionListener logic.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// ActionCommand Example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class ActionCommandExample {
public static void main(String[] args) {
JButton b0 = new JButton("yes");
JButton b1 = new JButton("no");
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if(command.equals("confirm")) {
// do something appropriate
}
else {
// do something else
}
}
};
b0.addActionListener(al);
b1.addActionListener(al);
b0.setActionCommand("confirm");
b1.setActionCommand("deny");
JFrame jframe = new JFrame();
Container cp = jframe.getContentPane();
cp.setLayout(new FlowLayout());
cp.add(b0);
cp.add(b1);
jframe.pack();
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.setVisible(true);
}
}
28-29 setActionCommand() methods are invoked for each of the JButtons.
15 The getActionCommand() method is invoked for the event to determine what should be done. Note that the names on the buttons becomes irrelevant, it is the ActionCommand that is important, so that if the names on buttons change (to a different language for example), or different components are used to generate the events, the action part of the logic can remain the same.
