📅  最后修改于: 2023-12-03 14:42:17.019000             🧑  作者: Mango
Java WindowListener接口是Java AWT包中提供的一个接口,用于响应与窗口(Window)相关的事件,例如窗口打开和关闭、大小和位置的更改等等。
WindowListener接口定义了以下7个方法:
public interface WindowListener extends EventListener {
public void windowOpened(WindowEvent e);
public void windowClosing(WindowEvent e);
public void windowClosed(WindowEvent e);
public void windowIconified(WindowEvent e);
public void windowDeiconified(WindowEvent e);
public void windowActivated(WindowEvent e);
public void windowDeactivated(WindowEvent e);
}
上述方法中,每个方法会传递一个WindowEvent对象,可以通过该对象获取有关窗口事件的详细信息。
WindowListener接口继承了EventListener,表示它是一种事件监听器。
每个方法对应了一个与窗口相关的事件:
windowOpened
:当一个窗口第一次打开时调用。windowClosing
:当用户尝试关闭窗口时调用。windowClosed
:当窗口已经被完全关闭时调用。windowIconified
:当一个窗口被最小化时调用。windowDeiconified
:当一个窗口从最小化状态回到正常状态时调用。windowActivated
:当一个窗口被激活时调用。windowDeactivated
:当一个窗口失去焦点时调用。下面的示例代码展示了如何使用WindowListener接口:
import java.awt.*;
import java.awt.event.*;
public class MyWindow extends Frame implements WindowListener {
public MyWindow() {
setTitle("My Window");
setSize(500, 500);
addWindowListener(this);
}
public void windowOpened(WindowEvent e) {
System.out.println("Window opened");
}
public void windowClosing(WindowEvent e) {
System.out.println("Window closing");
dispose();
System.exit(0);
}
public void windowClosed(WindowEvent e) {
System.out.println("Window closed");
}
public void windowIconified(WindowEvent e) {
System.out.println("Window iconified");
}
public void windowDeiconified(WindowEvent e) {
System.out.println("Window deiconified");
}
public void windowActivated(WindowEvent e) {
System.out.println("Window activated");
}
public void windowDeactivated(WindowEvent e) {
System.out.println("Window deactivated");
}
public static void main(String[] args) {
MyWindow window = new MyWindow();
window.setVisible(true);
}
}
在上述代码中,MyWindow类扩展了Frame类并实现了WindowListener接口。在MyWindow的构造函数中,我们添加了一个WindowListener实例(即this),以便我们可以处理窗口事件。
我们还覆盖了WindowListener接口的所有方法,以便我们可以在每个相关事件发生时打印相应的消息。
最后,我们实例化并显示MyWindow对象。