- 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 an action listener using method reference in Java?
In Java 8, lambda expression accepts an anonymous function as a parameter. In the case of providing an anonymous method, we can also pass references of existing methods using "::" symbol. A method reference enables us to do the same thing but with existing methods.
We can also implement an action listener for a JButton by using static method reference and referred using the class name.
Syntax
<Class-name>:: Method-name;
Example
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class MethodReferenceButtonListenerTest extends JFrame { private JButton button; public MethodReferenceButtonListenerTest() { setTitle("Method Reference Button Listener"); button = new JButton("Method Reference"); button.setBorder(BorderFactory.createLineBorder(Color.black)); button.addActionListener(MethodReferenceButtonListenerTest :: executeMethod); // static method reference getContentPane().add(button, BorderLayout.NORTH); setSize(400, 300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); } public static void main(String args[]) throws Exception { new MethodReferenceButtonListenerTest(); } public static void executeMethod(ActionEvent e) { JOptionPane.showMessageDialog(null, ((JButton)e.getSource()).getText()); } }
Output
Advertisements