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


Updated on: 11-Jul-2020

448 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements