Java/J2EE and SOA (325 Blogs) Become a Certified Professional
AWS Global Infrastructure

Programming & Frameworks

Topics Covered
  • C Programming and Data Structures (41 Blogs)
  • Comprehensive Java Course (2 Blogs)
  • Java/J2EE and SOA (324 Blogs)
  • Spring Framework (8 Blogs)
SEE MORE

MI-new-launch

myMock Interview Service for Real Tech Jobs

myMock-widget-banner-bg

How to Implement Action Listener in Java

Published on Oct 21,2019 56 Views

MI-new-launch

myMock Interview Service for Real Tech Jobs

myMock-mobile-banner-bg

myMock Interview Service for Real Tech Jobs

  • Mock interview in latest tech domains i.e JAVA, AI, DEVOPS,etc
  • Get interviewed by leading tech experts
  • Real time assessment report and video recording

When a user performs a certain action Java must be in a position to handle it effectively. Action listeners in Java come in very handy in such situations. In this article, we will be discussing the following points:

 

Introduction to Action Listener

As a programmer, it is your duty to define what an action listener can do for the user’s operation. For example, let us consider a simple scenario where the user selects a certain item from the menu bar or hits the enter key in a text field to go to a new line. Once such user functions are done, an “action performed” message is sent to all respective action listeners defined in the relevant component.

Below pictorially describes how to write an action listener:

Action-Listener-List

Here, the crucial and integral part is an object that can implement the Action Listener interface. This object must be identified by the program as an action listener on the button that is nothing but the event source.

Thus, utilizing the addActionListener method, when the user clicks the button it fires an action event. This invokes the action listener’s actionPerformed method. Please note that it is the only method in the ActionListener interface. A single argument to the method is an ActionEvent object, which provides information on event and its source

 

The Action Event Class

MethodsDescription
String getActionCommand()

Returns string associated with this action. Most objects that can fire action events support a method called setActionCommand, which allows you to set this string.

int getModifiers()

It Returns an integer, which the user was pressing when the during action event. Some ActionEvent-defined constants like SHIFT_MASK, CTRL_MASK, META_MASK, and ALT_MASK are used to determine the keys pressed. For instance, if a user selects a menu item then the expression is nonzero

Object getSource()

(in java.util.EventObject)

Returns the object that fired the event.

 

Implementing Action Listener in Java

package com.javapointers.javase;
 
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
 
public class ActionListenerTest implements ActionListener {
 
    JButton button;
    JFrame frame;
    JTextArea textArea;
 
    public ActionListenerTest() {
        button = new JButton("Click Me");
        frame = new JFrame("ActionListener Test");
        textArea = new JTextArea(5, 40);
 
        button.addActionListener(this);
        textArea.setLineWrap(true);
        frame.setLayout(new BorderLayout());
        frame.add(textArea, BorderLayout.NORTH);
        frame.add(button, BorderLayout.SOUTH);
        frame.pack();
 
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
 
    @Override
    public void actionPerformed(ActionEvent e) {
        textArea.setText(textArea.getText().concat("You have clicked
        the buttonn"));
    }
 
    public static void main(String args[]) {
        ActionListenerTest test = new ActionListenerTest();
    }
}

Action-Listener-in-Java

In the above code, an action listener is required to be implemented in a class before you can access it. So make sure you add in the implements keyword and the listener.

 

button.addActionListener(this)

It means the component button will be included in the components which are being tracked for an action event. It is mandatory to add a component to an action listener in order for you to add codes when the user clicks that particular component. Components that are not added with an action listener will fail to be monitored.

Now let us look at another simple example of the Action Listener in Java and how it works.

 

Example 2: 

Here there are 3 simple Java button objects where they are named as Red, Green and Blue. Depending on the button clicked the background screen colour changes. 

The below diagrams depicts the respective output of the code which is placed at the end of this document. Only one instance of the screen turning blue has been shown. Other colors like Red and green can be viewed by implementing this code.  

The button object “rb” is linked with the ActionListener. “this” parameter represents the ActionListener. Incase the linking is not done, the program will display 3 buttons but without event handling. 

getActionCommand() method of ActionEvent class throws back the label of the corresponding button clicked by the user as a string. str.

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

public class ButtonDemo extends Frame implements ActionListener
{
Button rb, gb, bb;		            // the three Button reference variables
public ButtonDemo()	                    // constructor to define the properties to a button
{
FlowLayout fl = new FlowLayout();	    // set layout to frame
setLayout(fl);

rb = new Button("Red");		    // convert variables into objects
gb = new Button("Green");
bb = new Button("Blue");

rb.addActionListener(this);		    // link Java buttons with ActionListener
gb.addActionListener(this);
bb.addActionListener(this);

add(rb);			            // add each Java button to the frame
add(gb);
add(bb);

setTitle("Button in Action");
setSize(300, 350);                      // frame dimensions, (width x height)
setVisible(true);			    // defining frame visible on monitor, default is setVisible(false)
}
// override only abstract method of ActionListener interface
public void actionPerformed(ActionEvent e)
{
String str = e.getActionCommand();	    // to identify the button clicked
System.out.println("You clicked " + str + " button");  //

if(str.equals("Red"))
{
setBackground(Color.red);
}
else if(str.equals("Green"))
{
setBackground(Color.green);
}
else if(str.equals("Blue"))
{
setBackground(Color.blue);
}
}
public static void main(String args[])
{
new ButtonDemo();                       // anonymous object of ButtonDemo to call the constructor
}
}

Action-Button

With this, we come to the end of this Action Listener in Java article. I hope you got an understanding of Action Listener in Java.

Check out the Java training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. Edureka’s Java J2EE and SOA training and certification course are designed for students and professionals who want to be a Java Developer. The course is designed to give you a head start into Java programming and train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Got a question for us? Please mention it in the comments section of this “Action Listener in Java” blog and we will get back to you as soon as possible.

Comments
0 Comments

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.