Christmas Pikachu 각각의 버튼의 콜백메소드
개발일지/자바

각각의 버튼의 콜백메소드

ZI_CO 2022. 9. 17.

 

 

실행 결과 메인

 

 

 

 

package blogpractice;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

class MyFrame extends JFrame implements ActionListener {

	JButton button1;
	JButton button2;
	JPanel jPanel;

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

	private void initData() {
		setTitle("리스너 사용방법 2");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setSize(500, 500);

		button1 = new JButton("button1");
		button2 = new JButton("button2");
		jPanel = new JPanel();
	}

	private void setInitLayout() {
		setVisible(true);
		setLayout(new FlowLayout());
		add(button2);
		add(button1);

	}

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

	@Override
	public void actionPerformed(ActionEvent e) {
		JButton targetButton = (JButton) e.getSource();
		if (targetButton.getText().equals(button1.getText())) {
			System.out.println("버튼 1이 눌러짐");
		} else {
			System.out.println("버튼 2 눌러짐");
		}
	}
}

public class EvListener_2 {
	public static void main(String[] args) {
		new MyFrame();
	}

}

 

댓글