WindowListener 监听窗口的所有行为,所有抽象方法必须全部实现
但是现实中很多时候只需要其中一个监听方法就够了 ,比如只监听关闭窗口的行为额 windowClosing(windowEvent)
/*窗口监听学习,WindowListener
* 只需要1个事件处理,但是必须实现接口中所有方法,不合适,下一节学习事件适配器
* */
package awt3yue1;
import java.awt.*;
import java.awt.event.*;
public class WindowListenerTest {
private Frame f = new Frame("窗口监听测试");
private TextArea ta = new TextArea(5,10);
public void init()
{
f.addWindowListener(new MyListener());
f.add(ta);
f.pack();
f.setVisible(true);
}
//创建窗口监听器,监听窗口的所有行为,并且选择性的执行每个行为对应的方法
//WindowListener这个接口有好几个抽象方法,必须全部实现,一个都不能少
class MyListener implements WindowListener
{
public void windowActivated(WindowEvent e)
{
ta.append("窗口被激活\n");
}
public void windowClosed(WindowEvent e)
{
ta.append("窗口被成功关闭\n");
}
public void windowClosing(WindowEvent e)
{
ta.append("用户关闭窗口\n");
//剖析这个代码的背后原理
System.exit(0);
}
public void windowDeactvated(WindowEvent e)
{
ta.append("窗口失去焦点\n");
}
@Override
public void windowOpened(WindowEvent e) {
ta.append("窗口被恢复\n");
}
@Override
public void windowIconified(WindowEvent e) {
ta.append("窗口被最小化\n");
}
@Override
public void windowDeiconified(WindowEvent e) {
ta.append("窗口被初次打开");
}
@Override
public void windowDeactivated(WindowEvent e) {
// TODO Auto-generated method stub
}
}
public static void main(String[] args)
{
new WindowListenerTest().init();
}
}
下一节学习 事件适配器