JFrame EventListener

JFrame Class를 상속받는 class 내부에 JButton 객체 생성하는 actionPerformed() 작성하기
May 30, 2024
JFrame EventListener

JFrame 상속 class MyFrame

package lect0530;

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

public class MyFrame extends JFrame {
    public MyFrame() {
        setTitle("My Frame");
        setSize(400, 300);
        Container containerPane = getContentPane();
        containerPane.setLayout(new FlowLayout());
        JButton button1 = new JButton("Hi! Button 1");
//        button1.addActionListener(new Listener());
        button1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
//                JButton button = new JButton("Pressed_Button");
                JOptionPane.showMessageDialog(MyFrame.this, "Hi! Button 1");
            }
        });
        JButton button2 = new JButton("Hi! Button 2");
        button2.addActionListener(new Listener());
        containerPane.add(button1);
        containerPane.add(button2);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }
    // anonymous method로 구현 가능
    private static class Listener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            JButton button = (JButton) e.getSource();
            button.setText("Pressed");
        }
    }

    public static void main(String[] args) {
        MyFrame myFrame = new MyFrame();
    }
}
  1. private static class 선언 또는

  2. 익명 함수화(버튼마다 구현) 방식

Share article

SW Engineering Blog