Java 中 WindowListener 接口的重要性是什么?


处理 **WindowEvent** 的类需要实现此接口,并且可以使用 **addWindowListener()** 方法将此类的对象注册到组件。

WindowListener 接口的方法

**WindowListener** 接口定义了 7 种处理窗口事件的方法

  • **void windowActivated(WindowEvent we)** − 当窗口被激活时调用。
  • **void windowDeactivated(WindowEvent we)** − 当窗口被取消激活时调用。
  • **void windowOpened(WindowEvent we)** − 当窗口打开时调用。
  • **void windowClosed(WindowEvent we)** − 当窗口关闭时调用。
  • **void windowClosing(WindowEvent we)** − 当窗口正在关闭时调用。
  • **void windowIconified(WindowEvent we)** − 当窗口最小化时调用。
  • **void windowDeiconfied(WindowEvent we)** − 当窗口恢复时调用。

语法

public interface WindowListener extends EventListener

示例

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class WindowListenerTest extends JFrame implements WindowListener {
   JLabel l1,l2;
   JTextField t1;
   JPasswordField p1;
   JButton b1;
   public WindowListenerTest() {
      super("WindowListener Test");
      setLayout(new GridLayout(3,2));
      l1 = new JLabel("Name");
      l2 = new JLabel("Password");
      t1 = new JTextField(10);
      p1 = new JPasswordField(10);
      b1 = new JButton("Send");
      add(l1);
      add(t1);
      add(l2);
      add(p1);
      add(b1);
      addWindowListener(this);
   }
   public static void main(String args[]) {
      WindowListenerTest wlt = new WindowListenerTest();
      wlt.setSize(375, 250);
      wlt.setResizable(false);
      wlt.setLocationRelativeTo(null);
      wlt.setVisible(true);
   }
   public void windowClosing(WindowEvent we) {
      this.setVisible(false);
      System.exit(0);
   }
   public void windowActivated(WindowEvent we) {
   }
   public void windowDeactivated(WindowEvent we) {
   }
   public void windowOpened(WindowEvent we) {
   }
   public void windowClosed(WindowEvent we) {
   }
   public void windowIconified(WindowEvent we) {
   }
   public void windowDeiconified(WindowEvent we) {
   }
}

输出


更新于: 2020-06-30

227 次查看

启动你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.