Button注册事件监听器
第一种方法
//创建监听器对象
MyButtonListener listener = new MyButtonListener();
//将监听器注册给按钮
button.addActionListener(listener);
}
public void showTime() {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String timestr = sdf.format(new Date());
timeLabel.setText(timestr);
}
private class MyButtonListener implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e) {
//System.exit(0);
//这里的.this是向外部类发送消息,
//.this.showTime();外部类调用内部类的属性和方法
//无名字冲突可省略Myframe.this.
Myframe.this.showTime();
}
}
}
第二种方法
//创建监听器对象
ActionListener listener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Myframe.this.showTime();
}
};
//将监听器注册给按钮
button.addActionListener(listener);
}
public void showTime() {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String timestr = sdf.format(new Date());
timeLabel.setText(timestr);
}
}
第三种(减少冗余,但是可读性降低了)
//将监听器注册给按钮
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Myframe.this.showTime();
}
});
}
public void showTime() {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String timestr = sdf.format(new Date());
timeLabel.setText(timestr);
}
}
第四种Lambda表达式
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Myframe.this.showTime();
}
});
//Lambda表达式 与上面的式子等价
button.addActionListener((e)->{
showTime();
});
}
public void showTime() {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String timestr = sdf.format(new Date());
timeLabel.setText(timestr);
}
}