swing

Swing ActionListener Java Example

In this post, we feature a comprehensive Swing ActionListener Java Example and we will analyze what is java listener.

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 a 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 that 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

Prerequisite
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 ActionListener in Java

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 java 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:
     
    ActionListenerExample.java
    1
    public class MyClass implements ActionListener {

  • Register an instance of the event handler class as a listener on one or more components. For example:
     
    ActionListenerExample.java
    1
    someComponent.addActionListener(instanceOfMyClass);

  • Include code that implements the methods in java listener interface. For example:
    ActionListenerExample.java
    1
    2
    3
    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:

ActionListenerExample.java

1
2
3
4
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:

ActionListenerExample.java

1
2
b = new Button("Click me");
b.addActionListener(this);

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:

ActionListenerExample.java

1
2
3
public void actionPerformed(ActionEvent e) {
         numClicks++;
         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

ActionListenerExample.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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");
                myWindow.setSize(350,100);
                myWindow.setVisible(true);
        }
 
        public AL(String title) {
 
                super(title);
                setLayout(new FlowLayout());
                addWindowListener(this);
                b = new Button("Click me");
                add(b);
                add(text);
                b.addActionListener(this);
        }
 
        public void actionPerformed(ActionEvent e) {
                numClicks++;
                text.setText("Button Clicked " + numClicks + " times");
        }
 
        public void windowClosing(WindowEvent e) {
                dispose();
                System.exit(0);
        }
 
        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:

ActionListener Java - ActionListenerExample
ActionListenerExample

5. Download the Source Code

This was an example of Java Swing ActionListener and an analysis of java listener.

Download
You can download the full source code of this example here: Swing ActionListener Java Example

Last updated on May 7th, 2020

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.
Subscribe
Notify of
guest

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

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button