由下表可以知道窗口事件只针对在窗口对象上发生的事件,它在用户打开、关闭、最小化、最大化窗口时发生,处理窗口的事件接口是WindowListener接口,窗口监听器的所有方法如下所示。
接下来将通过实例来讲解如何处理窗口事件的过程。这个实例主要用于展示当关闭一个窗口时其事件处理的过程。实例关键代码如下所示:
class windowhandler implements WindowListener{
public void windowOpened(WindowEvent e) {}
public void windowClosing(WindowEvent e) {}
public void windowClosed(WindowEvent e) {
JButton b1=new JButton("确定");
JButton b2=new JButton("取消");
JLabel l=new JLabel("确定关闭系统吗?");
JDialog d=new JDialog((JFrame)e.getSource(),"系统出错了!",true);
d.setSize(200, 100);
d.setLocation(0,0);
JPanel p=new JPanel();
p.setLayout(new GridLayout(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);
}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
}