Advanced Java Programming - Old Questions

7. What is action event? Discuss (5)

5 marks | Asked in 2074

The ActionEvent is generated when button is clicked or the item of a list is double-clicked. The listener related to this class is ActionListenerTo have any component listen for an ActionEvent, we must register the component with an ActionListener as: component.addActionListener(new MyActionListener()); and then write the  public void actionPerformed(ActionEvent e); method for the component to react to the event.

Example

import java.awt.event.*;

import javax.swing.*;

public class EventListener extends JFrame implements ActionListener {

   public EventListener(){

     JButton btn = new JButton("Click Me");

     add(btn);

     btn.addActionListener(this);         //registering the event handler

     setSize(100, 100);

     setVisible(true);

     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

@Override

public void actionPerformed(ActionEvent e) {

    JOptionPane.showMessageDialog(null, "Hello");

}

public static void main(String []a) {

   new EventListener();

  }

}

Here, whenever the “Click Me” button is clicked, an event is generated and a particular action of opening a dialog box and displaying message “Hello” happens.