This article shows how easy it is to use Lambda expressions (a new feature of the upcoming Java SE 8 platform) in order to make the event handler code in Swing concise and succinct.
Before Java 8, it’s very common that an anonymous class is used to handle click event of a JButton, as shown in the following code:
JButton button = new JButton("Click Me!"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { System.out.println("Handled by anonymous class listener"); } });
Here, an anonymous class that implements the ActionListener interface is created and passed into the addActionListener() method. And as normal, the event handler code is placed inside the actionPerformed() method.
Because the ActionListener interface defines only one method actionPerformed(), it is a functional interface which means there’s a place to use Lambda expressions to replace the boilerplate code. The above example can be re-written using Lambda expressions as follows:
button.addActionListener(e -> System.out.println("Handled by Lambda listener"));
Oops! It’s pretty nice, isn’t it?. If we want to use multiple statements then wrap them inside a block as follows:
button.addActionListener(e -> { System.out.println("Handled Lambda listener"); System.out.println("Have fun!"); });
Here’s code of a demo program which is a JFrame containing only one button which registers its click event with three different listeners:
import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * This simple Swing program demonstrates how to use Lambda expressions in * action listener. * * @author www.codejava.net */ public class ListenerLambdaExample extends JFrame { private JButton button = new JButton("Click Me!"); public ListenerLambdaExample() { super("Listener Lambda Example"); getContentPane().setLayout(new FlowLayout()); getContentPane().add(button); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { System.out.println("Handled by anonymous class listener"); } }); button.addActionListener(e -> System.out.println("Handled by Lambda listener")); button.addActionListener(e -> { System.out.println("Handled Lambda listener"); System.out.println("Have fun!"); }); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(300, 100); setLocationRelativeTo(null); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new ListenerLambdaExample().setVisible(true); } }); } }
Screenshot of the program:
Output in the console when the button is clicked:
Handled Lambda listener Have fun! Handled by Lambda listener Handled by anonymous class listener
Related Tutorials: