Home » Core Java » JAVA ActionEvent Example

About Jyoti Jha

Jyoti is a tech enthusiast and is an avid programmer. She holds a post graduation degree in (M.Tech) Computer Science Engineering from Thapar Univeristy, Patiala, India. Post her graduate studies, she has worked in Software companies such as SLK Software and Aricent, India as Software Engineer in various projects primarily in the field of Requirement analysis and design, implementing new algorithms in C++ and JAVA used in ISDN network and designing databases and. She is inquisitive about socio economic reforms as well as advancement in technical fronts and keep herself informed with TED talks and various blogs.

JAVA ActionEvent Example

1. Introduction

An Action can be used to separate functionality and state from a component. For example, if you have two or more components that perform the same function, consider using an Action object to implement the function.

An Action object is an action listener that provides not only action-event handling, but also centralized handling of the state of action-event-firing components such as tool bar buttons, menu items, common buttons, and text fields. The state that an action can handle includes text, icon, mnemonic, enabled, and selected status.

The ActionEvent is generated when button is clicked or the item of a list is double clicked.

2. Class declaration

Following is the declaration for java.awt.event.ActionEvent class:

ActionEventExample.java

public class ActionEvent
   extends AWTEvent

2.1 Field

Following are the fields for java.awt.event.ActionEvent class:

  • static int ACTION_FIRST — The first number in the range of ids used for action events.
  • static int ACTION_LAST — The last number in the range of ids used for action events.
  • static int ACTION_PERFORMED — This event id indicates that a meaningful action occurred.
  • static int ALT_MASK — The alt modifier.
  • static int CTRL_MASK — The control modifier.
  • static int META_MASK — The meta modifier.
  • static int SHIFT_MASK — The shift modifier.

2.2 Class constructors

  • ActionEvent(java.lang.Object source, int id, java.lang.String command): Constructs an ActionEvent object.
  • ActionEvent(java.lang.Object source, int id, java.lang.String command, int modifiers): Constructs an ActionEvent object with modifier keys.
  • ActionEvent(java.lang.Object source, int id, java.lang.String command, long when, int modifiers): Constructs an ActionEvent object with the specified modifier keys and timestamp.

2.3 Class methods

Method & Description

  • java.lang.String getActionCommand(): Returns the command string associated with this action.
  • int getModifiers(): Returns the modifier keys held down during this action event.
  • long getWhen(): Returns the timestamp of when this event occurred.
  • java.lang.String paramString(): Returns a parameter string identifying this action event.

3. AWT Event Handling

What is an Event?
Change in the state of an object is known as event i.e. event describes the change in state of source. Events are generated as result of user interaction with the graphical user interface components. For example, clicking on a button, moving the mouse, entering a character through keyboard, selecting an item from list, scrolling the page are the activities that causes an event to happen.

Types of Event
The events can be broadly classified into two categories:

  • Foreground Events – Those events which require the direct interaction of user.They are generated as consequences of a person interacting with the graphical components in Graphical User Interface. For example, clicking on a button, moving the mouse, entering a character through keyboard,selecting an item from list, scrolling the page etc.
  • Background Events – Those events that require the interaction of end user are known as background events. Operating system interrupts, hardware or software failure, timer expires, an operation completion are the example of background events.

3.1 What is Event Handling?

Event Handling is the mechanism that controls the event and decides what should happen if an event occurs. This mechanism has the code which is known as event handler that is executed when an event occurs. Java Uses the Delegation Event Model to handle the events. This model defines the standard mechanism to generate and handle the events. Let’s have a brief introduction to this model.

The Delegation Event Model has the following key participants namely:

Source – The source is an object on which event occurs. Source is responsible for providing information of the occurred event to it’s handler. Java provide as with classes for source object.

Listener – It is also known as event handler. Listener is responsible for generating response to an event. From java implementation point of view, the listener is also an object. Listener waits until it receives an event. Once the event is received , the listener process the event an then returns.

The benefit of this approach is that the user interface logic is completely separated from the logic that generates the event. The user interface element is able to delegate the processing of an event to the separate piece of code. In this model, Listener needs to be registered with the source object so that the listener can receive the event notification. This is an efficient way of handling the event because the event notifications are sent only to those listener that want to receive them.

3.2 Steps involved in event handling

  • The User clicks the button and the event is generated.
  • Now the object of concerned event class is created automatically and information about the source and the event get populated with in same object.
  • Event object is forwarded to the method of registered listener class.
  • the method is now get executed and returns.

Callback Methods

These are the methods that are provided by API provider and are defined by the application programmer and invoked by the application developer. Here the callback methods represents an event method. In response to an event java jre will fire callback method. All such callback methods are provided in listener interfaces.

If a component wants some listener will listen to it’s events the source must register itself to the listener.

4. AWT Event Listeners

The Event listener represents the interfaces responsible to handle events. Java provides us various Event listener classes but we will discuss those which are more frequently used. Every method of an event listener method has a single argument as an object which is subclass of EventObject class. For example, mouse event listener methods will accept instance of MouseEvent, where MouseEvent derives from EventObject.

Action listeners are probably the easiest — and most common — event handlers to implement. You implement an action listener to define what should be done when an user performs certain operation.

An action event occurs, whenever an action is performed by the user. Examples: When the user clicks a button, chooses a menu item, presses Enter in a text field. The result is that an actionPerformed message is sent to all action listeners that are registered on the relevant component.

To write an Action Listener, follow the steps given below:

1.Declare an event handler class and specify that the class either implements an ActionListener interface or extends a class that implements an ActionListener interface. For example:

ActionEventExample.java

public class MyClass implements ActionListener { 

2.Register an instance of the event handler class as a listener on one or more components. For example:

ActionEventExample.java

someComponent.addActionListener(instanceOfMyClass);

3.Include code that implements the methods in listener interface. For example:

ActionEventExample.java

public void actionPerformed(ActionEvent e) { 
    ...//code that reacts to the action... 
}

In general, to detect when the user clicks an onscreen button (or does the keyboard equivalent), a program must has an object that implements the ActionListener interface. The program must register this object as an action listener on the button (the event source), using the addActionListener method. When the user clicks the onscreen button, the button fires an action event. This results in the invocation of the action listener’s actionPerformed method (the only method in the ActionListener interface). The single argument to the method is an ActionEvent object that gives information about the event and its source.

Let us write a simple program which displays how many number of times a button is clicked by the user. First, here is the code that sets up the TextField , button and numClicks variable:

ActionEventExample.java

public class AL extends Frame implements WindowListener,ActionListener {
TextField text = new TextField(20);
Button b;
private int numClicks = 0;

In the above example, the event handler class is AL which implements ActionListener.

We would like to handle the button-click event, so we add an action listener to the button b as below:

ActionEventExample.java

b = new Button("Click me");
b.addActionListener(this); 

In the above code, Button b is a component upon which an instance of event handler class AL is registered.

Now, we want to display the text as to how many number of times a user clicked button. We can do this by writing the code as below:

ActionEventExample.java

public void actionPerformed(ActionEvent e) {
         numClicks++;
         text.setText("Button Clicked " + numClicks + " times");

Now, when the user clicks the Button b, the button fires an action event which invokes the action listener’s actionPerformed method. Each time the user presses the button, numClicks variable is appended and the message is displayed in the text field.

Here is the complete program(AL.java):

ActionEventExample.java

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

public class AL extends Frame implements WindowListener,ActionListener {
        TextField text = new TextField(20);
        Button b;
        private int numClicks = 0;

        public static void main(String[] args) {
                AL myWindow = new AL("My first window");
                myWindow.setSize(350,100);
                myWindow.setVisible(true);
        }

        public AL(String title) {

                super(title);
                setLayout(new FlowLayout());
                addWindowListener(this);
                b = new Button("Click me");
                add(b);
                add(text);
                b.addActionListener(this);
        }

        public void actionPerformed(ActionEvent e) {
                numClicks++;
                text.setText("Button Clicked " + numClicks + " times");
        }

        public void windowClosing(WindowEvent e) {
                dispose();
                System.exit(0);
        }

        public void windowOpened(WindowEvent e) {}
        public void windowActivated(WindowEvent e) {}
        public void windowIconified(WindowEvent e) {}
        public void windowDeiconified(WindowEvent e) {}
        public void windowDeactivated(WindowEvent e) {}
        public void windowClosed(WindowEvent e) {}

}

The Action Listener API

Because ActionListener has only one method, it has no corresponding adapter class.

actionPerformed(actionEvent): Called just after the user performs an action.

The ActionEvent Class

  • String getActionCommand(): Returns the string associated with this action. Most objects that can fire action events support a method called setActionCommand that lets you set this string.
  • int getModifiers(): Returns an integer representing the modifier keys the user was pressing when the action event occurred. You can use the ActionEvent-defined constants SHIFT_MASK, CTRL_MASK, META_MASK, and ALT_MASK to determine which keys were pressed. For example, if the user Shift-selects a menu item, then the following expression is nonzero: actionEvent.getModifiers() & ActionEvent.SHIFT_MASK
  • Object getSource(): Returns the object that fired the event.

5. Download The Source Code

This was an example of creation of JAVA Swing Table.

Download You can download the full source code of this example here: ActionEventExample

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Ivan
Ivan
2 years ago

Thanks!! you save my life