监听器
监听器 Listener,是Swing里界面事件处理的一种方式:
- 创建监听器对象 Listener
- 将监听器对象交给按钮
- 当按钮被点击时,Swing框架会调用监听器对象里的方法,进行处理。
示例代码:
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Demo1 {
private static void createGUI() {
MyFrame frame = new MyFrame("DemoFrame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
createGUI();
}
}
class MyFrame extends JFrame{
JLabel timeLabel = new JLabel("00:00:00");
JButton button = new JButton("显示时间");
public MyFrame(String title) {
super(title);
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
contentPane.add(button);
contentPane.add(timeLabel);
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 event) {
showTime();
}
}
}
演示:
点击按钮后:
使用匿名内部类进行简化:
由于在真正的程序里,这种小型的内部类数量很多,所以需要使用简化写法。
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
MyFrame.this.showTime();
}
});
使用Lambda表达式简化:
button.addActionListener((e)->{
showTime();
});
术语:回调
当我们调用系统的一个方法时,叫 Call(调用)
frame.setVisible(true);
frame.setText("HelloWorld");
当我们写一个方法被系统调用时,叫 Callback(回调)
public void actionPerformed(...)