Computer >> 컴퓨터 >  >> 프로그래밍 >> Java

Java에서 WindowListener 인터페이스가 중요한 이유와 7가지 핵심 메서드


Java GUI 프로그래밍에서 WindowEvent를 처리하려면 해당 클래스가 반드시 WindowListener 인터페이스를 구현해야 합니다. 구현된 클래스의 객체는 addWindowListener() 메서드를 통해 컴포넌트에 등록할 수 있으며, 이후 발생하는 모든 윈도우 관련 이벤트를 감지하고 원하는 동작을 수행할 수 있습니다.

WindowListener 인터페이스의 7가지 메서드

WindowListener 인터페이스는 윈도우 이벤트를 처리하기 위해 다음과 같은 7개의 메서드를 정의합니다.

  • void windowActivated(WindowEvent we) − 창이 활성화(포커스를 얻음)되었을 때 호출됩니다.
  • void windowDeactivated(WindowEvent we) − 창이 비활성화되었을 때 호출됩니다.
  • void windowOpened(WindowEvent we) − 창이 처음 열렸을 때 호출됩니다.
  • void windowClosed(WindowEvent we) − 창이 dispose() 호출 등으로 실제로 닫혔을 때 호출됩니다.
  • void windowClosing(WindowEvent we) − 사용자가 창 닫기를 시도하는 순간 호출됩니다.
  • void windowIconified(WindowEvent we) − 창이 최소화(아이콘화)되었을 때 호출됩니다.
  • void windowDeiconified(WindowEvent we) − 최소화된 창이 다시 복원되었을 때 호출됩니다.

구문(Syntax)

public interface WindowListener extends EventListener

예제 코드

다음은 JFrame에 WindowListener를 직접 구현하여 창 닫기 이벤트를 처리하는 간단한 로그인 폼 예제입니다. 인터페이스를 구현했기 때문에 사용하지 않는 메서드도 모두 빈 몸체로 작성해야 한다는 점에 주목하세요.

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) {}
}

실행 결과

Java에서 WindowListener 인터페이스가 중요한 이유와 7가지 핵심 메서드

참고: WindowAdapter를 활용한 더 깔끔한 코드

위 예제처럼 인터페이스를 직접 구현하면 필요하지 않은 메서드까지 모두 빈 몸체로 오버라이드해야 하는 번거로움이 있습니다. 이 경우 추상 클래스인 WindowAdapter를 상속받으면 실제로 필요한 메서드만 골라 재정의할 수 있어 코드가 훨씬 간결해집니다. 또한 자바 8 이후에는 람다 표현식을 지원하지 않는 인터페이스이므로, 간단한 윈도우 이벤트 처리 시에는 어댑터 클래스를 사용하는 것이 일반적인 권장 방식입니다.