Java Swing GUI

ActionListener – Java Swing – Example

In this tutorial, we are going to see an example of ActionListener in Java Swing. Java ActionListener is notified every time you click the button. It is notified by ActionEvent. The ActionListener interface exists in java.awt.event package. It has only one method actionPerformed(). This method is invoked automatically every time you click the button.

How to implement ActionListener

First you should implement ActionListener interface. If you implement ActionListener interface, you need to follow 3 steps:

1) Implement ActionListener interface:

public class MyJButtonActionListener implements ActionListener

2) Register the component with the Listener:


3) Override the method actionPerformed():

public void actionPerformed(ActionEvent e){
         // put the code here...



Example : ActionListener in Java Swing
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.*;

//1st step
public class MyJButtonActionListener implements ActionListener
  private static JTextField text;
  public static void main(String[] args) 
    JFrame frame = new JFrame("ActionListener Example");
    text = new JTextField();
    JButton btn = new JButton("Click here");
    MyJButtonActionListener instance = new MyJButtonActionListener();
    //2nd step

  //3rd step
  public void actionPerformed(ActionEvent e){
    text.setText("Welcome to StackHowTo");


mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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