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

Action command is used to handle event caused by the Buttons.

Example

 import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

public class ActionDemo extends JFrame implements ActionListener {

JLabel l1, l2, l3;

JTextField t1, t2, t3;

JButton b1, b2;

public ActionDemo() {

super("Handling Action Event");

l1 = new JLabel("Click on button to get result");

t1 = new JTextField(20);

b1 = new JButton("Demo Button");

b1.addActionListener(this);

setLayout(new FlowLayout(FlowLayout.CENTER, 150, 10));

add(l1);

add(t1);

add(b1);

setSize(400, 300);

setVisible(true);

}

public void actionPerformed(ActionEvent actionEvent) {

String str = actionEvent.getActionCommand(); //using action command

t1.setText("You have clicked " + str);

}

public static void main(String[] args) {

new ActionDemo();

}

}

In the above example if clicked on the Demo Button, with the help of the getActionCommand() method we will be able to see the click event done on the output.

Comments

Popular posts from this blog

What are the key challenges facing in Software Engineering? Explain.

EDI layered architecture

Description of Electronic Commerce Framework/Generic Framework of E-commerce.