Last Updated on 18 August 2019   |   Print Email
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.
1. Classic Listener Code in Java Swing
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.
2. Using Java Lambda expression for Listener Code in Swing
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:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.
It would be interesting to see your take on how these listeners can then be removed from the observable object.
Lots of examples of adding lambda and method-reference listeners to observables, but nothing on how they can be removed - which is necessary in a non-trivial system.
Comments
This was better laid out than anything on StackOverflow.
Lots of examples of adding lambda and method-reference listeners to observables, but nothing on how they can be removed - which is necessary in a non-trivial system.
Thanks for your useful advice.
SwingUtilities.invokeLater(LambdaExample::new);
Which is also cleaner.