How to Use Event Listeners in Java

Java Programming tutorials


In Java, an event is some action (or trigger) that your program has to listen for. There are two types of events in the Java programming language: low-level and semantic. Low-level events are low-level occurrences such as mouse clicks or keyboard strokes. The other kinds of events fall in the category of semantic, such as performing some action when a user types some characters.

To handle an event, developers need to implement an event listener. This handler will contain the method(s) that should be implemented. We discuss how to work with event listeners in this Java programming tutorial.

Read: Top Online Courses to Learn Java

How to Create an Event Listener in Java

First, it is important to mention that most listeners programmers will be dealing with are used for graphical components. Therefore, this section will begin by highlighting the listeners supported by all Swing components:

  • Component listener
  • Key listener
  • Mouse listener(s)
  • Hierarchy listener
  • Focus listener

If you are not familiar with Java GUI (graphical user interfaces), Swing is the library that all graphical components use in Java applications.

Let’s see how to create an event listener in Java. To do so, follow these three steps:

Step One: Create a class to implement a given listener interface:

public class XxxEventHandler implements XxxListener{

} // Xxx represents that particular listener you're implementing 

Step Two: Add the given listener to the component(s) for which you would like to listen for an event(s):

componentY.addXxxListener (this)

Step Three: Provide an implementation of the interface’s method(s):

public void methodX(XxxEvent e) {

}

In the next section we will discuss some specialized Java listeners.

Event Listeners in Java

The focus of this section is some of the design considerations that you need to keep in mind when writing your event classes:

  • You might decide to write an independent class for each event listener. However, this might come at a performance cost. Therefore, you can implement your program as a multithreaded application to overcome this. To learn about multithreading, check out our tutorial: Introduction to Multithreading in Java.
  • For security, you may need to implement your event classes as nested classes or declare them as private/protected classes. This restricts which classes can access your event handlers. You can learn more about this technique by reading our tutorial: Guide to Using Nested Classes in Java.

Action Listeners in Java

In most of the applications programmers create, you will use an action listener. Action listeners listen for actions that occur on any of your components. For example, button clicks or a keystroke. You can view a full of list components from the official Oracle page that support the ActionListener interface.

Below is a simple code example showing how to use an action listener in Java, in which a button changes to a random color whenever pressed:

import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.awt.event.*;
 
class ColoredButton implements ActionListener{
 
   JFrame frame = new JFrame();
   JButton demo = new JButton("Button Demo");
 
   ColoredButton(){
      
       demo.addActionListener(this);
 
       frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
       frame.add(demo);
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       frame.setSize(480,420);
       frame.setLocationRelativeTo(null);
       frame.setVisible(true);
   }
 
   public void actionPerformed(ActionEvent e) {
 
       Random random = new Random();
       int x = random.nextInt(255);
       int y = random.nextInt(255);
       int z = random.nextInt(255);
 
       Color randomColor = new Color(x,y,z);
       demo.setBackground(randomColor);
   }
      
   public static void main(String args[]){
 
       ColoredButton button1 = new ColoredButton();
    }
}

Read: Top Java IDEs and Code Editors

Key Listeners in Java

The Java program below provides an implementation of KeyListener. The KeyListener listens for when a key is pressed, typed, and released (in that order). Unlike the ActionListener interface that was shown earlier, the KeyListener has 3 methods that developers must implement in their event handler class: keyPressed(KeyEvent e), keyReleased(KeyEvent e), and keyTyped(KeyEvent e).

Below is an example of how to use KeyListener in Java:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
 
public class KeyStrokeEvent implements KeyListener{
 
   JFrame frame = new JFrame();
   TextField txtFld = new TextField(25);
 
   KeyStrokeEvent(){
 
       txtFld.addKeyListener(this);
 
       frame.add(txtFld);
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       frame.setSize(350,425);
       frame.setLocationRelativeTo(null);
       frame.setVisible(true);
   }
 
   public void keyPressed(KeyEvent e) {
       System.out.println("KEY PRESSED: " + e.KEY_PRESSED);
   }
 
   public void keyReleased(KeyEvent e) {
       // some code here
   }
 
   public void keyTyped(KeyEvent e) {
       // provide an implementation here
   }
  
   public static void main(String args[]){
 
       KeyStrokeEvent PressKey = new KeyStrokeEvent();
  
   }
}

The above program outputs the statement KEY PRESSED: 401 whenever a key is pressed. The value 401 is a static field that belongs to the KeyEvent class. This class has over 20 constant fields whose values you can look up here.

Notice that you have to provide the implementation for all three methods of the KeyEvent class. Otherwise, you will get a compilation error. This particular property is not particularly suitable, especially if you are only interested in implementing just one method. For some listeners, like the MouseListener, you will need to implement all five of its methods.

Java provides developers with adapter classes to help you overcome this. The adapter class, by default, defines the other unused methods. The adapter class for KeyEvent is KeyAdapter.

Here’s is a code example showing how to use an adapter class in Java (only one method is implemented):

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
 
public class KeyAdapterDemo extends KeyAdapter{
 
   JFrame frame = new JFrame();
   TextField txtFld = new TextField(20);
 
   KeyAdapterDemo(){
 
       txtFld.addKeyListener(this);
 
       frame.add(txtFld);
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       frame.setSize(420,340);
       frame.setLocationRelativeTo(null);
       frame.setVisible(true);
   }
 
   public void keyPressed(KeyEvent e) {
       int keyCode = e.getKeyCode();
       System.out.println("You pressed :" + e.getKeyText(keyCode));
   }
  
   public static void main(String args[]){
       KeyAdapterDemo myKey = new KeyAdapterDemo();
  
   }
}

The above program prints whichever key you press.

Final Thoughts on Event Listeners in Java

Generally, the goal is to ensure that your Java programs respond to events as fast as possible. Therefore, in whatever design you undertake, ensure that your Java applications respond quickly to events.

Read more Java programming tutorials and software development tips.

Like this post? Please share to your friends:
Leave a Reply

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: