What is the use of action command in event handling? Explain with example.

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).

Post a Comment

Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.