I am attempting to replace the inner class:
public void actionPerformed(ActionEvent event) {
red.addActionListener(e -> {
getContentPane().setBackground(Color.RED);
});
green.addActionListener(e -> {
getContentPane().setBackground(Color.GREEN);
});
blue.addActionListener(e -> {
getContentPane().setBackground(Color.BLUE);
});
clear.addActionListener(e -> {
getContentPane().setBackground(null);
});
}
in this program:
package com.IST242Apps;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ColorFrame extends JFrame{
JButton red, green, blue, clear;
public ColorFrame() { //frame parameters
super("ColorFrame");
setSize(500,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
FlowLayout flo = new FlowLayout();
setLayout(flo);
//create buttons
red = new JButton("RED");
add(red);
green = new JButton("GREEN");
add(green);
blue = new JButton("BLUE");
add(blue);
clear = new JButton("CLEAR");
add(clear);
//Something starts here -- the inner class?
ActionListener act = new ActionListener() { //
public void actionPerformed(ActionEvent event) { //when button is clicked
red.addActionListener(e -> {
getContentPane().setBackground(Color.RED); //make red
});
green.addActionListener(e -> {
getContentPane().setBackground(Color.GREEN); //make green
});
blue.addActionListener(e -> {
getContentPane().setBackground(Color.BLUE); //make blue
});
clear.addActionListener(e -> {
getContentPane().setBackground(null); //make clear
});
}
};
//comment: something ends here
//execute lambda expressions
red.addActionListener(act);
green.addActionListener(act);
blue.addActionListener(act);
clear.addActionListener(act);
setVisible(true); //make visible
}
public static void main(String args[]) {
new ColorFrame();
}
}
as a lambda expression. However, I'm confused on how to actually replace inner classes with lambda expressions as I've never done so before.
If you could also explain how lambda expressions work, as what ive seen on w3schools.
// numbers.forEach( (n) -> { System.out.println(n); } );
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(5);
numbers.add(9);
numbers.add(8);
numbers.add(1);
numbers.forEach( (n) -> { System.out.println(n); } );
(1) you reference something. (numbers)
(2) express some command. (forEach)
(3) set a parameter (n)
(4) express some code to be executed. ({System.out.println(n);})
// is n just referring to a non-existant variable?
CodePudding user response:
The equivalent lambda expression is:
ActionListener act = event -> { //when button is clicked
red.addActionListener(e -> {
getContentPane().setBackground(Color.RED); //make red
});
green.addActionListener(e -> {
getContentPane().setBackground(Color.GREEN); //make green
});
blue.addActionListener(e -> {
getContentPane().setBackground(Color.BLUE); //make blue
});
clear.addActionListener(e -> {
getContentPane().setBackground(null); //make clear
});
};