이벤트 리스너 작성해보기(내부클래스, 독립된 클래스, 익명 클래스)
★ 내부 클래스로 이벤트 리스너 작성.
- 클래스 안에 멤버처럼 클래스 작성.
- 이벤트 리스너를 특정 클래스에서만 사용할 때 적합.
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Test extends JFrame implements ActionListener {
Test() {
setTitle("Test");
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 프레임 윈도우를 닫으면 프로그램 종료
JButton btn = new JButton("Action");
btn.addActionListener(this);
add(btn);
setSize(300, 150);
setVisible(true); // 프레임이 화면에 나타나도록 설정
}
public static void main(String arg[]) {
new Test();
}
public void actionPerformed(ActionEvent e) {
JButton b = (JButton) e.getSource();
if (b.getText().equals("Action"))
b.setText("액션");
else
b.setText("Action");
}
}
★ 독립된 클래스로 이벤트 리스너를 작성.
- 이벤트 리스너를 완전한 클래스로 작성.
- 이벤트 리스너를 여러 곳에서 사용할 때 적합.
public class Test extends JFrame {
Test() {
setTitle("Test");
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton btn = new JButton("Action");
MyActionListener listener = new MyActionListener();
btn.addActionListener(listener);
add(btn);
setSize(300, 150);
setVisible(true);
}
public static void main(String arg[]) {
new Test();
}
}
class MyActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
JButton b = (JButton) e.getSource();
if (b.getText().equals("Action"))
b.setText("액션");
else
b.setText("Action");
}
}
★ 익명 클래스로 작성
- 클래스의 이름 없이 간단히 리스너 작성.
- 클래스 조차 만들 필요 없이 리스너 코드가 간단한 경우에 적합.
public class Test extends JFrame {
Test() {
setTitle("Test");
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton btn = new JButton("Action");
btn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
JButton b = (JButton) e.getSource();
if (b.getText().equals("Action"))
b.setText("액션");
else
b.setText("Action");
}
});
add(btn);
setSize(300, 150);
setVisible(true);
}
public static void main(String arg[]) {
new Test();
}
}
실행 결과