并不是所有的事件处理都像按钮点击那样简单。在正规的程序中,往往希望用户在确认没有丢失所做工作之后再关闭程序。当用户关闭框架时,可能希望弹出一个对话框来警告用户没有保存的工作有可能会丢失,只有在用户确认之后才退出程序。
当程序用户试图关闭一个框架窗口时,JFrame对象就是WindowEvent的事件源。如果希望捕获这个事件,就必须有一个适合的监听器对象,并将它添加到框架的窗口监听器列表中。
窗口监听器必须是实现WindowListener接口的类的一个对象。在WindowListener接口中包含7个方法。当发生窗口事件时,框架将调用这些方法响应7个不同的事件。从它们的名字就可以得知其作用,唯一的例外是在Windows下,通常将iconified称为minimized。
public interface WindowListener extends EventListener {
/**
* Invoked the first time a window is made visible.
*/
public void windowOpened(WindowEvent e);
/**
* Invoked when the user attempts to close the window
* from the window's system menu.
*/
public void windowClosing(WindowEvent e);
/**
* Invoked when a window has been closed as the result
* of calling dispose on the window.
*/
public void windowClosed(WindowEvent e);
/**
* Invoked when a window is changed from a normal to a
* minimized state. For many platforms, a minimized window
* is displayed as the icon specified in the window's
* iconImage property.
* @see java.awt.Frame#setIconImage
*/
public void windowIconified(WindowEvent e);
/**
* Invoked when a window is changed from a minimized
* to a normal state.
*/
public void windowDeiconified(WindowEvent e);
/**
* Invoked when the Window is set to be the active Window. Only a Frame or
* a Dialog can be the active Window. The native windowing system may
* denote the active Window or its children with special decorations, such
* as a highlighted title bar. The active Window is always either the
*