In Java's event handling model, especially with buttons or menu items, the action command is a String identifier associated with an ActionEvent. It helps determine which component triggered the event when multiple components share the same listener.
🔍 Why Use Action Commands?
- To distinguish between multiple event sources using a single
ActionListener. - Helpful when different buttons or menu items need different actions, but are handled by the same listener method.
🧪 Example: Action Command in Use
import javax.swing.*;
import java.awt.event.*;
public class ActionCommandExample extends JFrame implements ActionListener {
JButton btnSave, btnLoad;
public ActionCommandExample() {
setTitle("ActionCommand Example");
setSize(300, 150);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(null);
// Create buttons
btnSave = new JButton("Save");
btnLoad = new JButton("Load");
// Set positions
btnSave.setBounds(50, 30, 80, 30);
btnLoad.setBounds(150, 30, 80, 30);
// Set action commands (optional if button text is enough)
btnSave.setActionCommand("saveFile");
btnLoad.setActionCommand("loadFile");
// Register action listener
btnSave.addActionListener(this);
btnLoad.addActionListener(this);
// Add buttons to frame
add(btnSave);
add(btnLoad);
}
// Handle events
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand(); // Get action command
if (cmd.equals("saveFile")) {
JOptionPane.showMessageDialog(this, "Save button clicked");
} else if (cmd.equals("loadFile")) {
JOptionPane.showMessageDialog(this, "Load button clicked");
}
}
public static void main(String[] args) {
new ActionCommandExample().setVisible(true);
}
}
⚙️ How it Works:
btnSave.setActionCommand("saveFile")sets a custom command.- In
actionPerformed(),getActionCommand()returns"saveFile"or"loadFile". - Based on the command, the correct action is performed.
✅ Benefits:
- Clean and scalable code.
- Same listener can handle many components.
- Improves readability when button labels change (you can still use stable commands).