S.S.G

이벤트 리스너 작성해보기(내부클래스, 독립된 클래스, 익명 클래스) 본문

코딩/JAVA

이벤트 리스너 작성해보기(내부클래스, 독립된 클래스, 익명 클래스)

자유로운개발 2016. 7. 4. 14:27
반응형

 

 내부 클래스로 이벤트 리스너 작성.

 - 클래스 안에 멤버처럼 클래스 작성.

 - 이벤트 리스너를 특정 클래스에서만 사용할 때 적합.


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();

 }
}

 

 

실행 결과

 

 

 

 

 

 

 

반응형

'코딩 > JAVA' 카테고리의 다른 글

JRadioButton & Item  (0) 2016.07.05
MouseListener 사용 해보기  (0) 2016.07.04
Collections 클래스 활용  (0) 2016.07.04
HashMap<K,V>  (0) 2016.07.01
제네릭 컬렉션 활용 - ArrayList<E>  (0) 2016.07.01