// This example is from the book "Java in a Nutshell, Second Edition". // Written by David Flanagan. Copyright (c) 1997 O'Reilly & Associates. // You may distribute this source code for non-commercial purposes only. // You may study, modify, and use this example for any purpose, as long as // this notice is retained. Note that this example is provided "as is", // WITHOUT WARRANTY of any kind either expressed or implied. /* Modified by R. Brown 1/8/99: name change, doc tweak Add a button by subclassing an existing Applet; define adapter via lambda */ import java.applet.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Lambda extends Inner { JButton clearButton; public void init() { super.init(); /* call Inner.init() to initialize mouse... */ this.getContentPane().setLayout(new FlowLayout(FlowLayout.LEADING)); clearButton = new JButton("Clear"); /********************************************************************* Instead of defining a class to implement the interface ActionListener for "action" events for clearButton, we use Java 8's lambda feature. - The "lambda" expression e -> {...} is equivalent to new MyActionListener() plus the definition of the entire class MyActionListener in Subclass.java , except that no .class file is generated for MyActionListener when lambda expr. is compiled - Lambda expressions can only be used for interfaces that have only one abstract method. Thus we can use lambda for ActionListener but not for MouseMotionListener or MouseListener **********************************************************************/ clearButton.addActionListener(e -> { // clear the scribble getContentPane().repaint(); }); clearButton.setForeground(Color.black); clearButton.setBackground(Color.lightGray); this.getContentPane().add(clearButton); } }