more examples en
    
 

IMPLEMENTING AN ACTIONLISTENER USING A LAMBDA EXPRESSION

API

javax.swing.JFrame
javax.swing.JButton
javax.swing.JLabel
java.awt.GridLayout
java.awt.event.ActionListener
java.awt.event.ActionEvent

 



As of Java 8, any interface with only one abstract method can be used just like a functional interface; its abstract method can be implemented as a lambda expression.

 

 1 package at.krux.gui;

 2 import java.awt.GridLayout;
 3 import java.awt.event.ActionEvent;
 4 import java.awt.event.ActionListener;
 5 import javax.swing.JButton;
 6 import javax.swing.JFrame;
 7 import javax.swing.JLabel;

 8 public class ActionListenerLambdaExpression {

 9   JFrame frame;
10   JButton button;
11   JLabel label;
12   GridLayout grid;
	
13   ActionListenerLambdaExpression() {
14     this.frame = new JFrame();
15     this.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
16     this.button = new JButton("OK");
17     this.label = new JLabel("waiting for an ActionEvent...", JLabel.CENTER);
18     this.grid = new GridLayout(2,1);

19     this.frame.setLayout(grid);
		
20     this.button.addActionListener((evt) -> label.setText("an ActionEvent has occurred!"));
21     this.frame.add(label);
22     this.frame.add(button);
23     this.frame.setBounds(200, 200, 450, 250);
		
24     this.frame.setVisible(true);
25   }

26   public static void main(String[] args) {
		
27     new ActionListenerLambdaExpression();

28   }
29 }