event
Handle action events example
In this tutorial we are going to see how ActionListener works in Java. This is one of the most important components you have to work with when you’re developing a GUI Application. The ActionListener is able to monitor a number of important events that occur in GUI Apps.
In short, all you have to do to work with an ActionListener in Java is:
- Create an
ActionListenerinstance. - Override the methods that correspond to the events that you want to monitor about the components e.g,
actionPerformedand customize as you wish the handling of the respective events. Now every time one of these events occurs, the corresponding method will be executed. - Use
addActionListenerto add theActionListenerto a specific component.
Let’s take a closer look a the code snippet that follows:
package com.javacodegeeks.snippets.desktop;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Frame;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ActionListener {
public static void main(String[] args) {
// Create frame with specific title
Frame frame = new Frame("Example Frame");
// Create a component to add to the frame; in this case a text area with sample text
final TextArea textArea = new TextArea("Click button to handle button clicks...");
// Create a component to add to the frame; in this case a button
Button button = new Button("Click Me!!");
// Add a action listener to determine button clicks
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
textArea.setText(textArea.getText() + "nButton clicked");
}
});
// Add the components to the frame; by default, the frame has a border layout
frame.add(textArea, BorderLayout.NORTH);
frame.add(button, BorderLayout.SOUTH);
// Show the frame
int width = 300;
int height = 300;
frame.setSize(width, height);
frame.setVisible(true);
}
}
This was an example on how to work with ActionListener in Java.

