Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

ความสำคัญของอินเทอร์เฟซ WindowListener ใน Java

คลาสที่ประมวลผล WindowEvent ต้อง implement อินเทอร์เฟซนี้ และอ็อบเจกต์ของคลาสนี้สามารถลงทะเบียนกับคอมโพเนนต์ได้โดยใช้เมธอด addWindowListener()

เมธอดของ WindowListener Interface

WindowListener กำหนด 7 เมธอดสำหรับจัดการ Window Events

  • void windowActivated(WindowEvent we) - เรียกเมื่อหน้าต่างถูกทำให้ใช้งาน (activated)
  • void windowDeactivated(WindowEvent we) - เรียกเมื่อหน้าต่างถูกยกเลิกการใช้งาน (deactivated)
  • void windowOpened(WindowEvent we) - เรียกเมื่อหน้าต่างเปิด
  • void windowClosed(WindowEvent we) - เรียกเมื่อหน้าต่างปิดแล้ว
  • void windowClosing(WindowEvent we) - เรียกเมื่อหน้าต่างกำลังจะปิด
  • void windowIconified(WindowEvent we) - เรียกเมื่อหน้าต่างย่อเป็นไอคอน
  • void windowDeiconified(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) {}
}

ผลลัพธ์

ความสำคัญของอินเทอร์เฟซ WindowListener ใน Java