Full Stack Web Development Internship Program
- 29k Enrolled Learners
- Weekend/Weekday
- Live Class
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:
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:
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
Methods | Description |
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) |
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(); } }
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 } }
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 Online 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.
edureka.co