[JAVA] Event > Handler 수정 예제

정은아·2022년 8월 5일

implements ~Listenr를 받는 각종 event들을 handler로 수정하려면 어떻게 해야할까요?

package ja_0805;

import java.awt.Frame;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ActionEvent_4 extends Frame implements ActionListener {

	TextField txt_1, txt_2, txt_3;
	
	public ActionEvent_4(String str)
	{
		super(str);
		txt_1 = new TextField("문자를 입력하세요.", 20);
		txt_2 = new TextField("...", 20);
		txt_3 = new TextField("3번 ... ", 20);
		
		txt_1.addActionListener(this);
		txt_2.addActionListener(this);
		txt_3.addActionListener(this);
		
		add("North", txt_1);
		add("Center", txt_2);
		add("South", txt_3);
		
		setSize(300, 300);
		setVisible(true);
		
	}
	public static void main(String[] args) {
		
		new ActionEvent_4("Action Event Test~");
	}
	@Override
	public void actionPerformed(ActionEvent e) 
	{
		TextField obj = (TextField)e.getSource();
		
		if (obj == txt_1) 
		{
			txt_2.setText(txt_3.getText());
			txt_3.setText(txt_1.getText());
			txt_2.setFocusable(true);
			txt_1.setFocusable(false);
			txt_3.setFocusable(false);
		}
		else if(obj == txt_2)
		{
			txt_1.setText(txt_2.getText());
			txt_3.setText(txt_1.getText());
			txt_3.setFocusable(true);
			txt_1.setFocusable(false);
			txt_2.setFocusable(false);
		}
		else
		{
			txt_1.setText(txt_2.getText());
			txt_2.setText(txt_3.getText());
			txt_1.setFocusable(true); //true가 밑에 있으면 안된다. 항상 먼저 올라와 있어야 한다.
			txt_2.setFocusable(false);
			txt_3.setFocusable(false);
		}
	}
}

를 handler로 수정하겠습니다.

public class ActionEvent_4 extends Frame implements ActionListener { 

public class ActionEvent_4 extends Frame

으로 수정해줍니다. 아래에 class를 새로 만들어 거기에 implements해줄것이니까요

그 후

txt_1.addActionListener(this);
		txt_2.addActionListener(this);
		txt_3.addActionListener(this);

txt_1.addActionListener(new Handler());
		txt_2.addActionListener(new Handler());
		txt_3.addActionListener(new Handler());

로 수정해줍니다.

그 다음 Override위에 class를 새로 만들어줍니다.

class Handler implements ActionListener
{
}

를 써주면 끝입니다! handler가 적용된 소스를 this로 바꾸려면 반대로 하면 됩니다.

profile
꾸준함의 가치를 믿는 개발자

0개의 댓글