How to implement an action listener using method reference in Java?

Java 8Object Oriented ProgrammingProgramming

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


raja
Published on 18-Dec-2019 10:40:08
Advertisements