ActionListener is used to handle click event on clickable components like Button, MenuItem, JToggleButton, etc.

ActionListener Interface

As per the event delegation model we are going to implement this interface in our class. ActionListener consists of 1 method which is as below.

  1. public void actionPerformed(ActionEvent e)

To add ActionListener on any component the syntax is: btn.addActionListener(this);
For further reference you can refer my article on Event Handling Methodologies.

Program:

import java.awt.*;
import java.applet.*;
import java.awt.event.*;


public class AppletActionListener extends Applet implements ActionListener 
{
	Label l1,l2,l3;
	TextField t1,t2,ans;
	Button btn,btn2,btn3,btn4;
	public void init()
	{
		l1 = new Label("OP1: ");	
		l2 = new Label("OP2: ");	
		l3 = new Label("Ans: ");	
		t1 = new TextField("0",20);
		t2 = new TextField("0",20);
		ans = new TextField(20);
		btn = new Button("+");
		btn2 = new Button("-");
		btn3 = new Button("*");
		btn4 = new Button("/");
		btn.addActionListener(this);
		btn2.addActionListener(this);
		btn3.addActionListener(this);
		btn4.addActionListener(this);
		add(l1);add(t1);
		add(l2);add(t2);
		add(btn);add(btn2);add(btn3);add(btn4);
		add(l3);add(ans);


	}	
	public void actionPerformed(ActionEvent e) 
	{
		if(e.getSource()==btn)
		{
		ans.setText(Integer.parseInt(t1.getText()) + Integer.parseInt(t2.getText())+"");
		}
		else if(e.getSource()==btn2)
		{
		ans.setText(Integer.parseInt(t1.getText()) - Integer.parseInt(t2.getText())+"");
		}
		else if(e.getSource()==btn3)
		{
		ans.setText(Integer.parseInt(t1.getText()) * Integer.parseInt(t2.getText())+"");
		}
		else if(e.getSource()==btn4)
		{
		ans.setText(Integer.parseInt(t1.getText()) / Integer.parseInt(t2.getText())+"");
		}
		
	}
}
/*
<applet code="AppletActionListener" width="190" height="200"></applet>
*/