ActionListener – Click event handling
Action(Click) Event Delegation Model
Event Listeners:
Listener Interface: java.awt.event.ActionListener
Methods: public void actionPerformed(ActionEvent e)
Events:
java.awt.event.ActionEvent
Events Source:
Button, MenuItem E.g.
Button b = new Button("Ok"); b.addActionListener(this);
Applicable on:
ActionListener is used to handle click event on clickable entities.
Steps to apply an event handling
- Import class/classes: like import java.awt.event.*;
- Implement Listener interface in a class.
- Define all the methods of implemented interface and write the logic in appropriate method.
- Apply Listener to a component.
Program to Handle Click Event on a Button:
File Name: clickDemo.java
import java.awt.*; import java.applet.*; import java.awt.event.*; public class clickDemo extends Applet implements ActionListener { Button btn; TextField tf; public void init() { btn = new Button("Increment"); tf = new TextField("0", 20); add(tf); add(btn); btn.addActionListener(this); } public void actionPerformed(ActionEvent e) { int val = Integer.parseInt(tf.getText()); val++; tf.setText(val+""); } } /* <applet code="clickDemo" width="500" height="50"></applet> */
Points to be noted
1. actionPerformed() method will be automatically invoked whenever Button is clicked.
public void actionPerformed(ActionEvent e) { }
2. tf.getText() is used to retrieve current value of TextField named tf.
int val = Integer.parseInt(tf.getText()); val++; tf.setText(val+"");
3. In the above code snippet we have used tf.setText() method which takes a String as argument. But our variable “val” is int that’s why we have type cast it to String by appending “”.
Applying single event listener to multiple components.
Now we are planning 2 Buttons. 1) Increment 2) Decrement. Here the problem is we have only 1 method which will be automatically called on clicking any of the Button. But we would like to execute different logic in both the cases.
File Name: twoClickDemo.java
import java.awt.*; import java.applet.*; import java.awt.event.*; public class twoClickDemo extends Applet implements ActionListener { Button btn, btn2; TextField tf; public void init() { btn = new Button("Increment"); btn2 = new Button("Decrement"); tf = new TextField("0", 20); add(tf); add(btn); add(btn2); btn.addActionListener(this); btn2.addActionListener(this); } public void actionPerformed(ActionEvent e) { int val = Integer.parseInt(tf.getText()); if(e.getSource()==btn) { val++; } else { val--; } tf.setText(val+""); } } /* <applet code="twoClickDemo" width="500" height="50"></applet> */
Thank you sir. Please help me in Multithreading.
Was this answer helpful?
LikeDislikeRakesh, I will be uploadig Multithreading content as well as programs by tomorrow. You can refer the site tomorrow. Thanks for your feedback.
Was this answer helpful?
LikeDislike