ActionListener via Lambda

Created: 10.04.2014

ActionListener pre Java8

Before Java8, ActionListener were typically created like this:

public class SimpleActionListener extends JFrame{
	private static final long serialVersionUID = 1L;
	private JButton button;
	
	public SimpleActionListener() {
		super("Simple ActionListener");
		setSize(new Dimension(640,480));
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		button = new JButton("Button");
		button.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e) {
				System.out.println("print something");
			}
		});
		
		getContentPane().add(button, BorderLayout.CENTER);
	}
}

The compiler creates an inner anonymous class that might print a string or the content of a field on the view class. That's the way it worked for years and it will still work just fine even with the new JDK 8.

ActionListener with Lambda Expression

Lambda expressions can be used to replace simple ActionListener in Java desktop applications. Lambda expressions are short and easy to read, which means they reduce the code.

public class SimpleActionListener extends JFrame{
	private static final long serialVersionUID = 1L;
	private JButton button;
	
	public SimpleActionListener() {
		super("Simple ActionListener");
		setSize(new Dimension(640,480));
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		button = new JButton("Button");
		button.addActionListener(e ->{
			System.out.println("print something");
		});
		
		getContentPane().add(button, BorderLayout.CENTER);
	}
}