What is ActionListener ActionEvent with Example?

What is ActionListener ActionEvent with Example?

Every GUI component when interacted by the user (like by clicking over a button or pressing enter key in a text field etc.), the component generates an event. Handling the event and executing some method is known as event handling. Button generates an event known as ActionEvent and is handled by ActionListener interface

The events generated by different components have different names given by Java Designers. Of course, some events are common for a few components. For example, the event generated by button is known as ActionEvent (to be more precise, the event generated by button is represented in Java by the class java.awt.event.ActionEvent). Similarly, the event generated by a check box is known as ItemEvent and by a scrollbar is known as AdjustmentEvent etc. These examples refer software components. But, Java can handle the events generated by hardware components like mouse (known as MouseEvent) and keyboard (known as KeyEvent) etc.

To handle the events generated by the components (either or hardware or software), Java introduced listeners. That is, a listener can handle the event. All listeners are interfaces from java.awt.event package. Just like events come with name, the listeners also have names. For example, the listener that can handle the ActionEvent is known as ActionListener and similarly for ItemEvent it is known as ItemListener.

For a list and more on listeners read Java AWT Listeners.

Here, we are interested in Button, ActionEvent and ActionListener. Let us see a small example of how to handle ActionEvent with ActionListener.

The example contains two buttons Accept and Reject. A message is displayed as per the button user clicked. Observe, linking of ActionListener with buttons.

Screenshot when the buttons are clicked.


How to know which button user clicked?

String str = e.getActionCommand();

getActionCommand() method of ActionEvent class returns the label of the button user clicked. Now, the string str represents the label of the button user clicked. Programmer can differentiate which button user clicked with str. Using the handle str, the Programmer can do event handling.

1. For more detailed notes on each statement of the above code, read Java AWT Button – Learning GUI – 8 Steps
2. To know the internal mechanism of event handling with screenshots spread in two pages, read Java Event Handling

Leave a Reply

Your email address will not be published. Required fields are marked *