How to implement the listeners using lambda expressions in Java?

Java 8Object Oriented ProgrammingProgramming

When we are using a lambda expression for java listener, we do not have to explicitly implement the ActionListener interface. Instead, we can use the below syntax.

Syntax

button.addActionListener(e -> { // some statements });

An ActionListener interface defines only one method actionPerformed(). It is a functional interface which means that there's a place to use lambda expressions to replace the code.

Example

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class LambdaListenerTest extends JFrame {
   public static void main(String args[]) {
      new LambdaListenerTest();
   }
   private JButton button;
   public ClickMeLambdaTest() {
      setTitle("Lambda Expression Test");
      button = new JButton("Click Me!");
      button.addActionListener(ae -> button1Click());   // lambda expression for ActionListener 

      getContentPane().add(button, BorderLayout.NORTH);
      setSize(450, 300);
      setLocationRelativeTo(null);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setVisible(true);
   }
   private int clickCount = 0;
   public void button1Click() {
      clickCount++;
      if(clickCount == 1)
         button.setText("Clicked!!!");
      else
         button.setText("Clicked " + clickCount + " times!!!");
   }
}

Output


raja
Published on 12-Dec-2019 13:30:33
Advertisements