我正在嘗試替換內部類:
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);
});
}
在這個程式中:
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();
}
}
作為 lambda 運算式。但是,我對如何用 lambda 運算式實際替換內部類感到困惑,因為我以前從未這樣做過。
如果您還可以解釋 lambda 運算式的作業原理,就像我在 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) 你參考了一些東西。(數字)
(2) 表達一些命令。(forEach)
(3) 設定一個引數 (n)
(4) 表示一些要執行的代碼。({System.out.println(n);})
// n 只是指一個不存在的變數嗎?
uj5u.com熱心網友回復:
等效的 lambda 運算式是:
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
});
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/334818.html
標籤:爪哇
