How to Use Lambda Expressions to Handle Events in Java

In Java, you can use Lambda expressions to simplify classes that implement interfaces that have just one method — that is, interfaces that qualify as functional interfaces. The ActionListener interface is such an interface: It has just one method, named ActionPerformed.

When you use a Lambda expression, you do not have to explicitly implement the ActionListener interface. Instead, you can use code such as the following to add an event listener:

button1.addActionListener(e -> button1Click() );

Then the method button1Click will be called whenever the user clicks button1.

Check out this version of the ClickMe program that uses a Lambda expression to handle the button click event.

import javax.swing.*;
import java.awt.event.*;
public class ClickMeLambda
 extends JFrame
{
 public static void main(String [] args)
 {
  new ClickMeLambda();
 }
 private JButton button1;
 public ClickMeLambda()
 {
  this.setSize(300,150);
  this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  this.setTitle("I’m Listening");
  JPanel panel1 = new JPanel();
  button1 = new JButton("Click Me!");
  button1.addActionListener(e -> button1Click() );
  panel1.add(button1);
  this.add(panel1);
  this.setVisible(true);
 }
 private int clickCount = 0;
 public void button1Click()
 {
  clickCount++;
  if (clickCount == 1)
   button1.setText("I’ve been clicked!");
  else
   button1.setText("I’ve been clicked "
    + clickCount + " times!");
 }
}

Check out the features directly related to the use of the Lambda expression:

  button1.addActionListener(e -> button1Click() );

This statement uses a Lambda expression to add an action listener to handle button clicks. The Lambda expression simply calls the method button1Click whenever the user clicks the button.

 private int clickCount = 0;

The clickCount variable is declared as a class field.

 public void button1Click()

The button1Click method is called whenever the user clicks the button. This method changes the text that's displayed on the button's label.

Note that you could have eliminated the button1Click method altogether, and instead included its code directly in the Lambda expression, like this:

 button1.addActionListener(e ->
  {
   clickCount++;
   if (clickCount == 1)
    button1.setText("I’ve been clicked!");
   else
    button1.setText("I’ve been clicked "
     + clickCount + " times!");
  } );

However, this type of coding can quickly become unwieldy. So, as a rule, include the actual work done by an event handler in a separate method that's called via a Lambda expression when the event handler is set up.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement

Inside Dummies.com