JavaSwingJButton绑定事件之lambda写法-创新互联
《Java从入门到精通》(第5版)(明日科技)第255页,常用事件监听器部分写的太复杂了,绑定事件时还要专门写一个类,蛋疼!!!jetbrains idea推荐了lambda 写法。
import javax.swing.*;
import java.awt.*;
public class JPanelTest extends JFrame {
public JPanelTest() {
Container c = getContentPane();
c.setLayout(new GridLayout(2,1,10,10));
JPanel p1 = new JPanel(new GridLayout(1, 1, 10, 10));
JPanel p2 = new JPanel(new FlowLayout(FlowLayout.CENTER,10,10));
JLabel jl = new JLabel("我是小淘气", JLabel.CENTER);
p1.add(jl);
JButton b1 = new JButton(" 打屁屁");
//b1.setSize(5, 20);
JButton b2 = new JButton("不打屁屁");
//b2.setSize(5, 20);
p2.add(b1);
p2.add(b2);
c.add(p1);
c.add(p2);
b1.addActionListener(e ->jl.setText("不要啊!!!")); //lambda写法好简单
b2.addActionListener(e ->jl.setText("感谢不杀之恩!!!"));
setSize(500, 500);
setVisible(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new JPanelTest();
}
}
import javax.swing.*;
import java.awt.*;
public class SimpleEvent extends JFrame {
public SimpleEvent() {
setTitle("简单事件");
setLayout(new FlowLayout(FlowLayout.LEFT, 10, 10));
Container c = getContentPane();
JLabel jl = new JLabel("我是好孩子");
JButton jb = new JButton("我是按钮,点击我");
c.add(jl);
c.add(jb);
//setBounds(10, 10, 100, 100);
jb.addActionListener(e ->{ //lambda写法中多行命令时
jb.setText("我被单击了");
jl.setText("不要啊");
});
setSize(500, 500);
setVisible(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new SimpleEvent();
}
}
你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧
文章题目:JavaSwingJButton绑定事件之lambda写法-创新互联
文章源于:http://ybzwz.com/article/cesogo.html