JAVA

swing 이벤트 리스너(ActionListener)

jiyoon12 2025. 4. 29. 16:47
  • 단계별로 코드 수정하며 이해하기

 

  • 코드 구현하기
package _swing2;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * 자바는 단일 상속만을 지원한다. object 클래스 제외
 * 이벤트 리스너 예제 코드 작성해보기
 */

//ActionListener (인터페이스) -->
public class ColorChangeFrame extends JFrame implements ActionListener {


    private JButton button1;

    public ColorChangeFrame() {
        initData();
        setInitData();
        addEventListener();
    }

    private void initData() {
        setSize(500, 500);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        button1 = new JButton("button1");
    }

    private void setInitData() {
        setLayout(new FlowLayout());
        add(button1);
        setVisible(true);
    }

    private void addEventListener() {
        button1.addActionListener(this);
    }

    //테스트 코드
    public static void main(String[] args) {
        new ColorChangeFrame();
    }

    // 운영체제와 약속되어 있는 추상 메서드를 오버라이드 했다.
    // 이벤트가 발생되면 이 메서드를 자동으로 수행해(콜백) 미리 정해져 있는
    // 정보(객체)를 받을 수 있다.
    // 단, 어떤 컴포넌트가 이벤트를 실행시킬건지 먼저 등록 해주어야 한다.
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("actionPerformed() 메서드가 호출 되었다.");
        System.out.println(e.toString());
    }
}

 

  • 이벤트 리스너 구현하기
package _swing2;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ColorChangeFrame2 extends JFrame implements ActionListener {

    private JButton button1;
    private JButton button2;
    private JPanel panel;

    public ColorChangeFrame2() {
        initData();
        setInitLayout();
        addEventListener();
    }

    private void initData() {
        setSize(500, 500);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        panel = new JPanel();
        button1 = new JButton("click1");
        button2 = new JButton("click2");
    }

    private void setInitLayout() {
        setLayout(new BorderLayout());
        panel.setBackground(Color.YELLOW);
        add(panel, BorderLayout.CENTER);
        add(button1, BorderLayout.NORTH);
        add(button2, BorderLayout.SOUTH);

        setVisible(true);
    }

    // 이 메서드의 책임은 이벤트 리스너만을 등록 처리 한다.
    private void addEventListener() {
        button1.addActionListener(this); // 다형성
        button2.addActionListener(this);
    }

    // 이벤트 리스너 콜백 메서드
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("버튼이 눌러 졌습니다.");
        // 도전 과제
        // 어떻게 button1이 눌러졌는지 button2가 눌러졌는지 구분할까?
        System.out.println(e.getActionCommand());
        //getActionCommand --> String
        if(e.getActionCommand().equals("click1")){
            System.out.println("버튼1이 눌러졌어");
            panel.setBackground(Color.BLUE);
        }else{
            System.out.println("버튼2가 눌러졌어");
            panel.setBackground(Color.GREEN);
        }
    }

    public static void main(String[] args) {
        new ColorChangeFrame2();
    }
}

 

  • 이벤트 리스너와 다운캐스팅 구현하기
package _swing2;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ColorChangeFrame2 extends JFrame implements ActionListener {

    private JButton button1;
    private JButton button2;
    private JPanel panel;

    public ColorChangeFrame2() {
        initData();
        setInitLayout();
        addEventListener();
    }

    private void initData() {
        setSize(500, 500);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        panel = new JPanel();
        button1 = new JButton("클릭1");
        button2 = new JButton("버튼2");
    }

    private void setInitLayout() {
        setLayout(new BorderLayout());
        panel.setBackground(Color.YELLOW);
        add(panel, BorderLayout.CENTER);
        add(button1, BorderLayout.NORTH);
        add(button2, BorderLayout.SOUTH);

        setVisible(true);
    }

    // 이 메서드의 책임은 이벤트 리스너만을 등록 처리 한다.
    private void addEventListener() {
        button1.addActionListener(this); // 다형성
        button2.addActionListener(this);
    }

    // 이벤트 리스너 콜백 메서드
    @Override
    public void actionPerformed(ActionEvent e) {

        // JButton -> 다운 캐스팅
        JButton selectedButton = (JButton) e.getSource();
        System.out.println(selectedButton);
        System.out.println(selectedButton.getText());

        // 같은 객체의 주소값을 가리키는 비교
        if(selectedButton == button1){
            panel.setBackground(Color.GREEN);
        } else if (selectedButton == button2) {
            panel.setBackground(Color.BLUE);
        }
    }

    public static void main(String[] args) {
        new ColorChangeFrame2();
    }
}