 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to implement the listeners using lambda expressions in Java?
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
Advertisements
 