View RSS Feed

My Java Tips

Implementing ActionListener interface

Rate this Entry
by , 11-12-2011 at 05:54 PM (3045 Views)
ActionListener interface is used to perform actions on a performed event. In this post, I will write about its importance and usage.


ActionListener interface is part of java.awt.event package. It has only one abstract method that has to be implemented in the class implementing this interface.

Method signature:
void actionPerformed(ActionEvent e)

Consider the following scenario: you developed an GUI form for an application comprising of text fields, combo boxes and buttons. Then user fills the form he hits submit button. You want an action to be taken on this even. That action can be form validation or storing the entered data into database. Now this action is defined actionPerformed(…) method.

Time for an example:


Java Code:
import java.awt.*;
import java.awt.event.*; 

	public class MyFrame {
	  public static void main(String[] args){
	    Button b;
	    ActionListener a = new MyActionListener();
	    Frame f = new Frame("Java Frame");
	    f.add(b = new Button("Java"), BorderLayout.NORTH);
	    b.setActionCommand("Java");
	    b.addActionListener(a);
	    f.add(b = new Button("VB"), BorderLayout.CENTER);
	    b.addActionListener(a);
	    f.add(b = new Button("Exit"), BorderLayout.SOUTH);
	    b.setActionCommand("Exit");
	    b.addActionListener(a);
	    f.pack();
	    f.show();
	  }
	} 

	class MyActionListener implements ActionListener {
	  public void actionPerformed(ActionEvent ae) {
	    String s = ae.getActionCommand();
	    if (s.equals("Exit")) {
	      System.exit(0);
	      }
	      else if (s.equals("Java")) {
	        System.out.println("Java rocks.");
	        }
	        else {
	          System.out.println(s + " clicked");
	          }
	    }
}
I created a Frame with 3 buttons. On clicking Java button, “Java rocks” is printed on the console, on clicking VB button, “VB clicked” is printed on the console, and on pressing Exit button, quit operation is performed.

We simple created an additional class and implemented the ActionListener interface. Then we defined the actionPerformed(…) method according to our requirements. ActionEvent, which is a parameter of actionPerformed(…) method can a method named getActionCommand() to get the name of the even generating command.

Now Listener class is ready. Simply create an instance of it and attach it to the command using addActionListener(…) method. Now whenever command is given, action listener will act accordingly.

I have kept this simple. Reuse the example above and play with it.

Happy coding.

Submit "Implementing ActionListener interface" to Facebook Submit "Implementing ActionListener interface" to Digg Submit "Implementing ActionListener interface" to del.icio.us Submit "Implementing ActionListener interface" to StumbleUpon Submit "Implementing ActionListener interface" to Google

Comments