AWT에서 반응에 의한 동작을 하고 싶을때 이벤트 핸들링이 필요하다.
이번 포스팅에서는 AWT에서 이벤트 핸들링을 하는 3가지 방법에 대해서 기록해보고자 한다.
들어가기 앞서 핸들러와 리스너에 대해서 알아보았다.
전부터 이 두개의 차이점이 뭔지 몰랐었다. 두개가 비슷한 말이겠거니 하고 사용했다.
핸들러와 리스너의 차이점은 주로 이벤트 처리 방식과 코드 구조에서 나타납니다. 핸들러는 이벤트 발생 시 실행되는 코드 자체를 의미하고, 리스너는 이벤트를 감지하고 처리하는 메커니즘을 제공합니다.
컴포넌트들은 리스너를 등록하기 위한 여러 메소드들을 제공한다.
public void addActionListener(ActionListener a)
public void addActionListener(ActionListener a)
public void addActionListener(ActionListener a)
public void addTextListener(TextListener a)
public void addTextListener(TextListener a)
public void addItemListener(ItemListener a)
public void addItemListener(ItemListener a)
public void addActionListener(ActionListener a)
public void addItemListener(ItemListener a)
import java.awt.*;
import java.awt.event.*;
// implements를 이용한 이벤트 핸들링
public class AEvent extends Frame implements ActionListener {
TextField tf;
AEvent() {
// 컴포넌트 생성
tf = new TextField();
tf.setBounds(60, 50, 170, 20);
Button b = new Button("click me");
b.setBounds(100, 120, 80, 30);
// 리스너 등록
b.addActionListener(this);
// 프레임에 컴포넌트 추가 및 설정
add(b);
add(tf);
setSize(300, 300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
tf.setText("Welcome");
}
public static void main(String[] args) {
new AEvent();
}
}
ActionListener를 implements해서 버튼 컴포넌트에서 리스너를 등록했다.
b.addActionListener(this)
를 통해서 AEvent의 인스턴스가 이벤트로 등록이 되며
actionPerformed
메소드를 재정의하여 행동을 정의한다.
import java.awt.*;
import java.awt.event.*;
// 외부 클래스로 이벤트 핸들링 구현
public class AEvent2 extends Frame {
TextField tf;
AEvent2() {
// 컴포넌트 생성
tf = new TextField();
tf.setBounds(60, 50, 170, 20);
Button b = new Button("click me");
b.setBounds(100, 120, 80, 30);
// 리스너 등록
Outer o = new Outer(this);
b.addActionListener(o);
// 프레임에 컴포넌트 추가 및 설정
add(b);
add(tf);
setSize(300, 300);
setLayout(null);
setVisible(true);
}
public static void main(String[] args) {
new AEvent2();
}
}
import java.awt.event.*;
public class Outer implements ActionListener{
AEvent2 obj;
Outer(AEvent2 obj){
this.obj = obj;
}
public void actionPerformed(ActionEvent e){
obj.tf.setText("welcome");
}
}
Outer o = new Outer(this);
외부클래스를 불러와서 리스너를 등록하는 방식으로
클래스 재사용에 염두하여 작성할때 사용하면 될 듯 하다.
import java.awt.*;
import java.awt.event.*;
// 익명 클래스로 이벤트 핸들링 구현
public class AEvent3 extends Frame {
TextField tf;
AEvent3() {
tf = new TextField();
tf.setBounds(60, 50, 170, 20);
Button b = new Button("click me");
b.setBounds(50, 120, 80, 30);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
tf.setText("hello");
}
});
add(b);
add(tf);
setSize(300, 300);
setLayout(null);
setVisible(true);
}
public static void main(String[] args) {
new AEvent3();
}
}
익명함수를 활용해서 구현하는 방법으로 리스너가 등록하는 곳에서 재정의까지 구현한다.
일회성으로 구현하며 가독성을 높힐 수 있을 것 같다.b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){ tf.setText("hello"); } });