by Dinesh Thakur Category: Swing

The action event occurs when you perform an action on a component such as clicking a button, double clicking a list item, selecting a menu item etc. Objects representing action events are created from ActionEvent class.

The corresponding listener interface for ActionEvent class is ActionListener. Each listener for ActionEvent should implement the ActionListener interface. This interface defines the following method to handle ActionEvent generated by a user interface component.

void actionPerformed(ActionEvent e)

It is called when ActionEvent is fired by any registered component.

import javax.swing.*;

import java.awt.*;
import java.awt.event.*;
class ActionListenerExample extends JFrame implements ActionListener
{
    JLabel lblData;
    JButton btnOk,btnCancel;
    ActionListenerExample()
    {
      setLayout(new FlowLayout());
      lblData = new JLabel("Click any button to display data");
      btnOk=new JButton("OK");
      btnCancel = new JButton("Cancel");
      //Register the current(this);
      btnOk.addActionListener(this);
      btnCancel.addActionListener(this);
      add(lblData);
      add(btnOk);
      add(btnCancel);
    }
 
   public void actionPerformed(ActionEvent e)
   {
    if(e.getSource() == btnOk)
       lblData.setText("OK Button is Clicked ");
    else
       lblData.setText("Cancel Button is Clicked ");
   }
}
 class ActionListenerJavaExample
 {
    public static void main(String args[])
    {
         ActionListenerExample frame = new ActionListenerExample();
        frame.setTitle("ActionListener in Java Swing Examples");
        frame.setBounds(200,150,180,150);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
   }
 }

ActionListener in Java Swing Examples



About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.



Related Articles