import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Main extends JFrame{
private JButton jb;
public Main(){
this.setBounds(200,200,200,200);
this.setTitle("lambda测试");
jb = new JButton("click");
jb.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("clicked");
}
});
this.add(jb);
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new Main();
}
}
将注释掉的部分改成下面一句即可:
jb = new JButton("click");
// jb.addActionListener(new ActionListener() {
// @Override
// public void actionPerformed(ActionEvent e) {
// System.out.println("clicked");
// }
// });
jb.addActionListener(event -> System.out.println("Hello") );
运行可看到: