Home » Desktop Java » awt » event » Handle action events example

About Ilias Tsagklis

Ilias Tsagklis
Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.

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 ActionListener instance.
  • Override the methods that correspond to the events that you want to monitor about the components e.g, actionPerformed and 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 addActionListener to add the ActionListener to 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.

(No Ratings Yet)
Start the discussion Views Tweet it!

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

 

Leave a Reply

avatar
  Subscribe  
Notify of