Home » Desktop Java » swing » Java Swing ActionListener Example

About Jyoti Jha

Jyoti Jha
Jyoti is a tech enthusiast and is an avid programmer. She holds a post graduation degree in (M.Tech) Computer Science Engineering from Thapar Univeristy, Patiala, India. Post her graduate studies, she has worked in Software companies such as SLK Software and Aricent, India as Software Engineer in various projects primarily in the field of Requirement analysis and design, implementing new algorithms in C++ and JAVA used in ISDN network and designing databases and. She is inquisitive about socio economic reforms as well as advancement in technical fronts and keep herself informed with TED talks and various blogs.

Java Swing ActionListener Example

Swing is a GUI widget toolkit for Java. It is part of Oracle’s Java Foundation Classes (JFC) – an API for providing a graphical user interface (GUI) for Java programs.

1. Introduction

Swing was developed to provide a more sophisticated set of GUI components than the earlier Abstract Window Toolkit (AWT). JAVA provides a rich set of libraries to create Graphical User Interface in platform independent way.

2. Java Swing

Unlike AWT, Java Swing provides platform-independent and lightweight components. The javax.swing package provides classes for java swing API

2.1 MVC Architecture

Swing API architecture follows loosely based MVC architecture in the following manner.

  • A Model represents component’s data.
  • View represents visual representation of the component’s data.
  • Controller takes the input from the user on the view and reflects the changes in Component’s data.
  • Swing component have Model as a seperate element and View and Controller part are clubbed in User Interface elements. Using this way, Swing has pluggable look-and-feel architecture.

Every user interface considers the following three main aspects:

  • UI elements : These are the core visual elements the user eventually sees and interacts with. GWT provides a huge list of widely used and common elements varying from basic to complex.
  • Layouts: They define how UI elements should be organized on the screen and provide a final look and feel to the GUI (Graphical User Interface).
  • Behavior: These are events which occur when the user interacts with UI elements.

2.2 Swing Features

Light Weight – Swing component are independent of native Operating System’s API as Swing API controls are rendered mostly using pure JAVA code instead of underlying operating system calls.

  • Rich controls – Swing provides a rich set of advanced controls like Tree, TabbedPane, slider, colorpicker, table controls.
  • Highly Customizable – Swing controls can be customized in very easy way as visual apperance is independent of internal representation.
  • Pluggable look-and-feel– SWING based GUI Application look and feel can be changed at run time based on available values.

2.3 Setup

Popular Java Editors:
To write your java programs you will need a text editor. There are even more sophisticated IDE available in the market. But for now, you can consider one of the following:

  • Notepad: On Windows machine you can use any simple text editor like Notepad TextPad.
  • NetBeans: is a Java IDE that is open source and free which can be downloaded from http://www.netbeans.org/index.html.
  • Eclipse: is also a java IDE developed by the eclipse open source community and can be downloaded from http://www.eclipse.org

This example is developed on Eclipse therefore a compatible Eclipse IDE is required to be installed on the system.
We also need WindowBuilder tool to be installed on Eclipse IDE for the easiness of the work.

3. How to Write an Action Listener

Action listeners are probably the easiest — and most common — event handlers to implement. You implement an action listener to define what should be done when an user performs certain operation.
An action event occurs, whenever an action is performed by the user. Examples: When the user clicks a button, chooses a menu item, presses Enter in a text field. The result is that an actionPerformed message is sent to all action listeners that are registered on the relevant component.

To write an Action Listener, follow the steps given below:

  • Declare an event handler class and specify that the class either implements an ActionListener interface or extends a class that implements an ActionListener interface. For example:

    public class MyClass implements ActionListener { 
  • Register an instance of the event handler class as a listener on one or more components. For example:

  • Include code that implements the methods in listener interface. For example:

    public void actionPerformed(ActionEvent e) { 
        ...//code that reacts to the action... 

In general, to detect when the user clicks an onscreen button (or does the keyboard equivalent), a program must have an object that implements the ActionListener interface. The program must register this object as an action listener on the button (the event source), using the addActionListener method. When the user clicks the onscreen button, the button fires an action event. This results in the invocation of the action listener’s actionPerformed method (the only method in the ActionListener interface). The single argument to the method is an ActionEvent object that gives information about the event and its source.

Let us write a simple program which displays how many number of times a button is clicked by the user. First, here is the code that sets up the TextField , button and numClicks variable:


public class AL extends Frame implements WindowListener,ActionListener {
TextField text = new TextField(20);
Button b;
private int numClicks = 0;

In the above example, the event handler class is AL which implements ActionListener.
We would like to handle the button-click event, so we add an action listener to the button b as below:


b = new Button("Click me");

In the above code, Button b is a component upon which an instance of event handler class AL is registered.
Now, we want to display the text as to how many number of times a user clicked button. We can do this by writing the code as below:


public void actionPerformed(ActionEvent e) {
         text.setText("Button Clicked " + numClicks + " times");

Now, when the user clicks the Button b, the button fires an action event which invokes the action listener’s actionPerformed method. Each time the user presses the button, numClicks variable is appended and the message is displayed in the text field.

3.1 The Action Listener API

The ActionListener Interface
Because ActionListener has only one method, it has no corresponding adapter class.

    • actionPerformed(actionEvent): Called just after the user performs an action

The ActionEvent Class

  • String getActionCommand():Returns the string associated with this action. Most objects that can fire action events support a method called setActionCommand that lets you set this string.
  • int getModifiers():Returns an integer representing the modifier keys the user was pressing when the action event occurred. You can use the ActionEvent-defined constants SHIFT_MASK, CTRL_MASK, META_MASK, and ALT_MASK to determine which keys were pressed. For example, if the user Shift-selects a menu item, then the following expression is nonzero:
    actionEvent.getModifiers() & ActionEvent.SHIFT_MASK
  • Object getSource():Returns the object that fired the event.

4. Code & Output


import java.awt.*;
import java.awt.event.*;

public class AL extends Frame implements WindowListener,ActionListener {
        TextField text = new TextField(20);
        Button b;
        private int numClicks = 0;

        public static void main(String[] args) {
                AL myWindow = new AL("My first window");

        public AL(String title) {

                setLayout(new FlowLayout());
                b = new Button("Click me");

        public void actionPerformed(ActionEvent e) {
                text.setText("Button Clicked " + numClicks + " times");

        public void windowClosing(WindowEvent e) {

        public void windowOpened(WindowEvent e) {}
        public void windowActivated(WindowEvent e) {}
        public void windowIconified(WindowEvent e) {}
        public void windowDeiconified(WindowEvent e) {}
        public void windowDeactivated(WindowEvent e) {}
        public void windowClosed(WindowEvent e) {}


When the code is executed, output will look like the one below:



5. Download The Source Code

This was an example of Java Swing ActionListener.

You can download the full source code of this example here: Actionlistenerexample
(+1 rating, 1 votes)
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


This site uses Akismet to reduce spam. Learn how your comment data is processed.

Notify of