- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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
- Related Articles
- How to implement LongUnaryOperator using lambda in Java?
- How to implement IntUnaryOperator using lambda in Java?
- How to implement LongConsumer using lambda in Java?
- How to implement IntBinaryOperator using lambda expression in Java?
- How to implement ToIntBiFunction using lambda expression in Java?
- How to implement ToDoubleBiFunction using lambda expression in Java?
- How to implement ToLongFunction using lambda expression in Java?
- How to implement ToLongBiFunction using lambda expression in Java?
- How to implement DoubleToIntFunction using lambda expression in Java?
- How to implement DoubleToLongFunction using lambda expression in Java?
- How to implement PropertyChangeListener using lambda expression in Java?
- How to implement DoubleFunction using lambda expression in Java?
- How to implement ToDoubleFunction using lambda expression in Java?
- How to implement DoubleConsumer using lambda expression in Java?
- How to implement the ObjIntConsumer interface using lambda expression in Java?

Advertisements