dreamsys software

Java 8 Lambda Expressions Tutorial

Listeners

This next section will show how you can use lambdas for listeners. Here is a sample where we create two JFrames in Swing, we show the old way with one and the new way with the other.

import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class SwingTest {
  public static void main(String []args) {
    makeFrameOldWay();
    makeFrameNewWay();
  }

  public static void makeFrameOldWay() {
    JButton btn = new JButton("Click Me");
    JComboBox cmb = new JComboBox();
    JFrame f = makeFrame(btn, cmb);

    btn.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        System.out.println("Button Clicked");
      }
    });

    cmb.addItemListener(new ItemListener() {
      public void itemStateChanged(ItemEvent e) {
        System.out.println("Select Event On: " + e.getItem());
      }
    });

    f.setVisible(true);
  }

  public static void makeFrameNewWay() {
    JButton btn = new JButton("Click Me");
    JComboBox cmb = new JComboBox();
    JFrame f = makeFrame(btn, cmb);

    btn.addActionListener(e -> System.out.println("Button Clicked"));
    cmb.addItemListener(e -> System.out.println("Select Event On: " + e.getItem()));

    f.setVisible(true);
  }

  public static JFrame makeFrame(JButton btn, JComboBox cmb) {

    cmb.setModel(new DefaultComboBoxModel<String>(new String[]{
      "Item 1",
      "Item 2",
      "Item 3",
      "Item 4",
      "Item 5",
    }));

    JFrame f = new JFrame("Old Way");
    f.getContentPane().setLayout(new GridLayout(2, 1));
    f.getContentPane().add(cmb);
    f.getContentPane().add(btn);
    f.pack();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    return f;
  }
}

Notice how again in the old way, the code is very verbose with lots of boiler plate code, we create an instance of an interface and override it's method to place our code for the handler.

btn.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent e) {
	System.out.println("Button Clicked");
  }
});

cmb.addItemListener(new ItemListener() {
  public void itemStateChanged(ItemEvent e) {
	System.out.println("Select Event On: " + e.getItem());
  }
});

Using lambdas, it's again as easy as one line of code for each listener:

btn.addActionListener(e -> System.out.println("Button Clicked"));
cmb.addItemListener(e -> System.out.println("Select Event On: " + e.getItem()));

Up until now, we've shown primarily that using lambdas helps you reduce code, in the next section we will also show how it makes it easier to keep your code DRY (Don't Repeat Yourself).


Prev (Map/Reduce) | Next (DRY)


Blog Entries
Blob Entry 1
Blob Entry 2
Blob Entry 3
Blob Entry 4
Blob Entry 5
Blob Entry 6