Java Reference
In-Depth Information
Problem
You want to use Java 8's lambda expressions to simplify GUI programming.
Solution
Write the lambda expression as the argument to, for example, JCompon-
ent.addActionListener() .
Discussion
The most common event method in Swing is JComponent's addActionListener() method.
Because ActionListener is a functional method, as defined in Chapter 9 , it can be used dir-
ectly with lambda expressions:
/** Demonstrate a JButton with Lambda Action Listeners */
public
public class
class ButtonDemo2L
ButtonDemo2L extends
extends JFrame {
private
private static
static final
final long
long serialVersionUID = 1L ;
public
public ButtonDemo2L () {
super
super ( "ButtonDemo Lambda" );
setDefaultCloseOperation ( JFrame . EXIT_ON_CLOSE );
setLayout ( new
new FlowLayout ());
JButton
b ;
add ( b = new
new JButton ( "A button" ));
// Minimalist style
b . addActionListener ( e -> JOptionPane . showMessageDialog ( this
this ,
"Thanks for pushing my first button!" ));
add ( b = new
new JButton ( "Another button" ));
// Longer style, with { } around body.
b . addActionListener ( e -> {
JOptionPane . showMessageDialog ( this
this ,
"Thanks for pushing my second button!" );
}
);
pack ();
}
public
public static
static void
void main ( String [] args ) {
Search WWH ::




Custom Search