Adapter:因为本来监听的时候应该使用接口Listener的,比如WindowListener,但是因为窗口(或者鼠标、键盘)有很多事件,所以在接口中定义了好几个抽象函数。如果直接实现接口的话需要把所有的抽象函数一一实现过去,这不划算,所以Java定义了适配器,用空函数实现了所有的抽象函数。我们自己定义的时候继承适配器类就等于实现了Listener接口,同时只需重写我们需要的函数就可以了。
监听窗口关闭:
方法一:用户试图从窗口的系统菜单中关闭窗口时调用。
方法二:因对窗口调用 dispose 而将其关闭时调用
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class Test3{
int i = 0;
JFrame f;
JPanel p;
JButton b;
JLabel l;
Test3(){
f = new JFrame();
p = new JPanel();
b = new JButton("Press Me");
l = new JLabel("Init...");
f.addWindowListener(
new WindowAdapter(){
public void windowClosing(WindowEvent e){
JOptionPane.showMessageDialog(f, "已经关掉窗口!");
System.exit(0);
}
});
b.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
l.setText(i++ + " time");
}
});
p.setLayout(new GridLayout(3,1));
p.add(l);
p.add(b);
f.add(p);
f.setTitle("Adapter_Test");
f.setBounds(250, 350, 300, 300);
f.setVisible(true);
}
public static void main(String Args[]){
new Test3();
}
} /*
1.点击按钮实现计数
2.点击Adapter_Test关闭按钮 弹出消息对话框 关闭窗口。
*/