EVENT HANDLING: EVENT AND LISTENER (ACTIONLISTENER)

What Will I Learn?

  • The user will learn the concept of Event Handling.
  • The user will learn the use of Events and Listeners.
  • The user will also learn how the ActionListener Interface is used to listen for an event and execute code.

Requirements

  • A computer System is required for this tutorial.
  • Java Software Development Kit(JDK) must be installed on your computer.
  • An Integrated Development Environment(IDE) such as Eclipse or NetBeans is required to be installed on your computer.

Get JDK here

Get Eclipse here

Get NetBeans here

Difficulty

This tutorial contains a little more advanced codes than the previous ones, however, the codes are not so difficult. I would rate the difficulty level as Intermediate.

Tutorial Contents

Picking up from where I stopped at the last tutorial, we have learnt:

JTEXTFIELD

  • The Concept.
  • How to create a JTextField Object and add it to a JFrame container.

JPASSWORDFIELD

  • The Concept
  • How to create a JTextField Object and add it to a JFrame container.

These two Swing components have been created and are just on the screen. An operation needs to happen if the user enters login details and hits the “Enter” button.
This brings us to the next topic…..

EVENT HANDLING: EVENT AND LISTENER (ACTIONLISTENER)

The process by which a program waits or listens to receive an event in order to execute a set of actions is called Event Handling. Examples of events include: Button Clicks, Mouse Movements, and Enter Button.

An event listener is a procedure or function in a computer program that waits for an event to occur; that event may be a user clicking or moving the mouse, pressing a key on the keyboard, or an internal timer or interrupt. The listener is in effect a loop that is programmed to react to an input or signal.

Event listeners represent the interfaces responsible to handle events. Java provides various Event listener classes, however, we will talk about one in this tutorial. Every method of an event listener method has a single argument as an object which is the subclass of EventObject class. For example, button event listener methods will accept instance of ActionEvent, where ActionEvent derives from EventObject.

In essence, the program listens for an event, when an event occurs, the program uses the event listeners as interfaces to handle these events and then a block of code is executed.
The code executed can be determined by the event that occurred.

6.png

7.png

EVENT LISTENER CODE BLOCK

private class newClass implements ActionListener {
        public void actionPerformed(ActionEvent event) {
            String displayMessage = "";
            if (event.getSource() == field) 
                displayMessage = String.format("Your Username is %s", event.getActionCommand());
            else if (event.getSource() == password)
                displayMessage = String.format("Your Username is %s", event.getActionCommand());
            JOptionPane.showMessageDialog(null, displayMessage);
        }
    }
OBJECT OF NEWCLASS CODE BLOCK
newClass eventHandler = new newClass();
        field.addActionListener(eventHandler);
        password.addActionListener(eventHandler);

When the new class which implements the ActionListener interface is created, an object of the new class is also created. the

.addActionListerer[]

method is then used to pass execution instructions to the JTextfield and JPasswordField components.

EVENTLISTENER CLASS
private class newClass implements ActionListener {

ActionListener is an interface (not a class) that contains a single method which is…

public void actionPerformed( ActionEvent evt)

A class that implements the interface must contain an actionPerformed() method. The ActionEvent parameter is an Event object that represents an event (a button click).

public void actionPerformed(ActionEvent event) {

This is the single method for the listener interface for receiving action events. The ActionEvent is a class and event is an instance of that class. ***event *** can be used to call it’s properties.

String displayMessage = ;

A variable of String type is declared and an empty String message is assigned to it.

If (event.getSource() == field)

getSource() is specified by the EventObject class that ActionEvent is a child of . This gives you a reference to the object that the event came from.

This simply means, where an action has occurred.

The conditional statement interprets: Where an action has occurred is equal to field.

displayMessage = String.***format***(, event.getActionCommand())

getActionCommand() gives you a String representing the action command. For JTextField, it will automatically give you the value of the text field. This simply returns the command that was entered. This assigns the command to the String variable displayMessage

The Program displays a pop up showing the user the entry the user made.

else if (event.getSource() == password)

This is a nested if statement. It is an alternative to the first if statement.

This simply means if an event occurred is equal to password, like the first statement.

displayMessage = String.***format***(, event.getActionCommand())

getActionCommand() gives you a String representing the action command.
The Program displays a pop up showing the user the entry the user made. This assigns the command to the String variable displayMessage

Just like the previous statement.

JOptionPane.***showMessageDialog***(null, displayMessage)

The .showMessageDialog from the JOptionPane class finally outputs the pop up message to the screen for the user to see.

NOTE

In addition to the import statements from the last tutorial, ActionListener and ActionEvent classes are imported because methods in the class will be used as Listeners to execute a block of code.

FULL CODE BLOCK

EVENTLISTNER CODE BLOCK
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
public class eventHandler extends JFrame{
    private JLabel text;
    private JTextField field;
    private JPasswordField password;
    public eventHandler() {
        super("JTextField Demo");
        setLayout(new FlowLayout());
        text = new JLabel("Enter Username and Password");
        text.setToolTipText("Login Details");
        add(text);
        field = new JTextField("Username", 15 );
        add(field);
        password = new JPasswordField("Password", 15);
        add(password);
        newClass eventHandler = new newClass();
        field.addActionListener(eventHandler);
        password.addActionListener(eventHandler);
    }
    private class newClass implements ActionListener {
        public void actionPerformed(ActionEvent event) {
            String displayMessage = "";
            if (event.getSource() == field) 
                displayMessage = String.format("Your Username is %s", event.getActionCommand());
            else if (event.getSource() == password)
                displayMessage = String.format("Your Username is %s", event.getActionCommand());
            JOptionPane.showMessageDialog(null, displayMessage);
        }
    }
}
EVENTLISTNERMAIN CODE BLOCK
import javax.swing.JFrame;
public class eventHandlerMain {
    public static void main (String args []) {
        eventHandler textObject = new eventHandler();
        textObject.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        textObject.setSize(350,150);
        textObject.setVisible(true);
    }
}

1.png

When the program is run and user enters Username and hits the "Enter" button, the program uses the ActionListener interface to listen to the event. Once an event is registered i.e "hitting enter button", the program displays the command entered by user.

2.png

Program returns command when user hits "Enter" button.

3.png

4.png

Source Codes from Github Account.

You can get the codes here if you want to try it on your own.

REFERENCES

Curriculum

Similar posts already posted on Utopian are:



Posted on Utopian.io - Rewarding Open Source Contributors

H2
H3
H4
3 columns
2 columns
1 column
Join the conversation now
Logo
Center