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);
}
}