由下表可以知道窗口事件只针对在窗口对象上发生的事件,它在用户打开、关闭、最小化、最大化窗口时发生,处理窗口的事件接口是WindowListener接口,窗口监听器的所有方法如下所示。
接下来将通过实例来讲解如何处理窗口事件的过程。这个实例主要用于展示当关闭一个窗口时其事件处理的过程。实例关键代码如下所示:
classwindowhandlerimplementsWindowListener{
publicvoidwindowOpened(WindowEvent e) {}
publicvoidwindowClosing(WindowEvent e) {}
publicvoidwindowClosed(WindowEvent e) {
JButton b1=newJButton("确定");
JButton b2=newJButton("取消");
JLabel l=newJLabel("确定关闭系统吗?");
JDialog d=newJDialog((JFrame)e.getSource(),"系统出错了!",true);
d.setSize(200, 100);
d.setLocation(0,0);
JPanel p=newJPanel();
p.setLayout(newGridLayout(1,2));
d.add(p,"South");
d.add(l,"Center");
p.add(b1);
p.add(b2);
d.setVisible(true);
b1.setVisible(true);
b2.setVisible(true);
l.setVisible(true);
}
publicvoidwindowIconified(WindowEvent e) {}
publicvoidwindowDeiconified(WindowEvent e) {}
publicvoidwindowActivated(WindowEvent e) {}
publicvoidwindowDeactivated(WindowEvent e) {}
}