How to use event listeners in Java

Textbooks for Java programming
In Java, an event is some action (or trigger) that your program must do 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. Other types of events fall into the semantic category, such as performing some action when the user types some characters.

To process the event, developers must implement event listener. This handler will contain the method(s) to be implemented. In this Java programming guide, we discuss how to work with event listeners.

Read: The best online courses to learn Java

How to create an event listener in Java

First, it’s important to mention that most of the listeners that developers will be dealing with are used for graphics components. Therefore, this section will begin by highlighting the listeners that everyone supports Swing components:

  • Component listener
  • The key listener
  • Mouse listener(s).
  • Hierarchy Listener
  • Listener focus

If you are not familiar with Java GUI (Graphical User Interfaces), Swing is a library used by all graphics components in Java applications.

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

The first step: Create a class to implement the default listener interface:

public class XxxEventHandler implements XxxListener

 // Xxx represents that particular listener you're implementing 

Second step: Add the given listener to the component(s) for which you want to listen for event(s):

componentY.addXxxListener (this)

The third step: Ensure the interface method(s) are implemented:

public void methodX(XxxEvent e) 



In the next section, we’ll discuss some specialized Java listeners.

Java event listeners

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

  • You may choose to write an independent class for each event listener. However, this can come at a performance cost. Therefore, you can implement your program as a multi-threaded application to overcome this. To learn more about multithreading, see our guide: 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 limits which classes can access your event handlers. You can learn more about this technique by reading our guide: A Guide to Using Nested Classes in Java.

Action listeners in Java

In most applications that developers create, you will use listener action. Action listeners listen for actions that occur on any of your components. For example, button clicks or keystrokes. You can see the full list of supported components on the official Oracle site ActionListener interface.

Below is a simple code example that shows how to use an action listener in Java, where a button changes color to a random color whenever it is 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: The best Java IDEs and code editors

Key listeners in Java

The Java program below provides the implementation KeyListener. The KeyListener listens for when a key is pressed, typed, and released (in that order). Unlike ActionListener interface 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 usage 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 makes a statement KEY PRESSED: 401 whenever a key is pressed. Value 401 is a static field belonging to KeyEvent class. This class has over 20 constant fields whose values ​​you can view here.

Note that you must provide an implementation for all three methods KeyEvent class. Otherwise you will get a compilation error. This particular property is not particularly convenient, especially if you are interested in implementing only one method. For some listeners, like MouseListeneryou will need to implement all five of its methods.

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

Here is a code example that shows how to use the 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 program above prints whatever key you press.

Final thoughts on event listeners in Java

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

Read more Java programming guides and software development tips.

Source link

Leave a Reply

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