카테고리 없음

# 45 ComponentEvent , ContainerEvent, FocusEvent,TextEvent

오늘의 진 2022. 8. 8. 14:40

ComponentEvent 

 

[  ComponentEvent 내부의 매소드들  ]

componentResized  컴포넌트의 사이즈가 변경되면 발동
componentMoved 컴포넌트가 움직이면 발동
componentShown 컴포넌트가 보이게 되면 발동
componentHidden 컴포넌트가 숨겨지면(보이지않으면) 발동

 

package ja_0808;

import java.awt.Button;
import java.awt.Frame;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;

public class Component_1 extends Frame implements ComponentListener, ActionListener {

	TextArea txt;
	Button btn;

	public Component_1(String title) {
		super(title);

		btn = new Button("화면에서 잠시 사라짐 ~");
		btn.addActionListener(this);
		add("South", btn);

		txt = new TextArea();
		add("Center", txt);
		addComponentListener(this); // 프레임에 달아준것이다. 

		setSize(300, 300);
		setVisible(true);

	}

	public static void main(String[] args) {
		new Component_1("Compinent Event Test ~");
	}

	@Override
	public void actionPerformed(ActionEvent e) { // 버튼에 달아준 이벤트

		try {
			this.setVisible(false); // 화면에서 사라짐
			Thread.sleep(3000);// 3초
		} catch (InterruptedException e1) {
			e1.printStackTrace();

		}
		this.setVisible(true);

	}

	@Override
	public void componentResized(ComponentEvent e) { //크기변경 감지
		txt.append("컴포넌트 크기 변경 ~~~~ \n");
		//크기변경이 감지되면 다음의 텍스트를 txt에 추가해라 라는 말 

	}

	@Override
	public void componentMoved(ComponentEvent e) { // 이동 감지
		txt.append("컴포넌트 이동 변경 %%%%% 변경 ~ \n");

	}

	@Override
	public void componentShown(ComponentEvent e) { // 나타남감지
		txt.append("컴포넌트가 화면에 나타남 ^^^^^^^ ~ \n");

	}

	@Override
	public void componentHidden(ComponentEvent e) { // 사라지게함 감지
		txt.append("컴포넌트가 숨겨짐 @@@@@@@@ ~ \n");

	}

}

 

 

 

 

 

 

 

 

 

 

ContainerEvent

 

(예) - 액션리스너 하나만을 이용해서 버튼을 눌렀을때 체크박스를 확인하고 결과를 도출하는 방법 

package ja_0808;

import java.awt.Button;
import java.awt.Checkbox;
import java.awt.CheckboxGroup;
import java.awt.Color;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class CheckBoxEventTest_1 extends Frame {
	
	
	Label q1,q2,q3;
	Label score;
	Checkbox q1cb1, q1cb2, q1cb3, q1cb4;
	Checkbox q2cb1, q2cb2, q2cb3, q2cb4;
	Checkbox q3cb1, q3cb2, q3cb3, q3cb4;
	CheckboxGroup group ,group2 ; 
	Button end;
	
	public CheckBoxEventTest_1(String title) {
		super(title);
		
		setSize(500,300);
		setLayout(new GridLayout(20,1));
		
		q1 = new Label("1. 다음 중 ActionEvent의 "+"actionPerformd() 메서드가 호출 되는 경우는 ?");
		q1cb1 = new Checkbox("Button을 눌렀을때");
		q1cb2 = new Checkbox("TextField에서 Enter키를 눌렀을때");
		q1cb3 = new Checkbox("MenuItem 을 클릭했을때");
		q1cb4 = new Checkbox("List에서 더블클릭으로 Item을 선택 했을때");
		
		
		q2 = new Label("2. Frame의 기본 LayOutManager는 ? (하나만 고르시오)");
		
		group = new CheckboxGroup();
		q2cb1 = new Checkbox("FlowLayout",group,false);
		q2cb2 = new Checkbox("GridLayout",group,false);
		q2cb3 = new Checkbox("BorderLayout",group,false);
		q2cb4 = new Checkbox("CardLayout",group,false);
		
		q3 = new Label("3. Panel의 기본 LayOutManager는 ? (하나만 고르시오)");
		
		group2 = new CheckboxGroup();
		q3cb1 = new Checkbox("FlowLayout",group2,false);
		q3cb2 = new Checkbox("GridLayout",group2,false);
		q3cb3 = new Checkbox("BorderLayout",group2,false);
		q3cb4 = new Checkbox("CardLayout",group2,false);
		
		
		
		
		score = new Label("**** 결과 : ");
		end = new Button("이 버튼을 누르면 결과를 알 수 있습니다.");
		end.setBackground(Color.green);
		
		end.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				float totalScore = 0.0f;
				
				if(q1cb1.getState())  totalScore +=12.5f;
				if(q1cb2.getState())  totalScore +=12.5f;
				if(q1cb3.getState())  totalScore +=12.5f;
				if(q1cb4.getState())  totalScore +=12.5f;
				
				if(q2cb3.getState())  totalScore +=25.0f;
				if(q3cb1.getState())  totalScore +=25.0f;
				
				score.setText("당신의 점수는 "+totalScore+"점 입니다.");
				
			}
		});
		
		add(q1);
		add(q1cb1);
		add(q1cb2);
		add(q1cb3);
		add(q1cb4);
		add(new Label("   "));
		add(q2);
		add(q2cb1);
		add(q2cb2);
		add(q2cb3);
		add(q2cb4);
		add(new Label("   "));
		add(q3);
		add(q3cb1);
		add(q3cb2);
		add(q3cb3);
		add(q3cb4);
		
		add(end);
		add(score);
		setVisible(true);
		

	}
	
	public static void main(String[] args) {
		new CheckBoxEventTest_1("Score Test");
	}
	
	
	

}

 

 

FocusEvent

package ja_0808;

import java.awt.Button;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.TextArea;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

public class Focus_1 extends Frame implements FocusListener {

	Button btn1, btn2;
	TextArea txt_info;

	public Focus_1(String title) {
		super(title);

		txt_info = new TextArea();
		btn1 = new Button("왼쪽 버튼");
		btn2 = new Button("오른쪽 버튼");

		btn1.addFocusListener(this);
		btn2.addFocusListener(this);

		Panel panel = new Panel();
		panel.add(btn1);
		panel.add(btn2);

		add("Center", txt_info);
		add("South", panel);

		setSize(300, 200);
		setVisible(true);

	}

	public static void main(String[] args) {
		new Focus_1("Focus Test");
	}

	@Override
	public void focusGained(FocusEvent e) {
		Button obj = (Button) e.getSource();

		if (obj == btn1) {
			txt_info.append(btn1.getLabel() + "포커스 얻음 \n");
		} else {
			txt_info.append(btn2.getLabel() + "포커스 얻음~~~~ \n");
		}

	}

	@Override
	public void focusLost(FocusEvent e) {
		Button obj = (Button) e.getSource();

		if (obj == btn1) {
			txt_info.append(btn1.getLabel() + "포커스 잃음 !!!\n");
		} else {
			txt_info.append(btn2.getLabel() + "포커스 잃음 !!! \n");
		}

	}

}

TextEvent

package ja_0808;

import java.awt.Frame;
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.TextEvent;
import java.awt.event.TextListener;

public class TextEvent_1 extends Frame implements TextListener {

	TextField txt;
	Label lbl_info;

	public TextEvent_1(String title) {
		super(title);

		txt = new TextField("텍스트 입력 ...", 20);
		txt.addTextListener(this);
		txt.selectAll();

		lbl_info = new Label("          ");
		add("Center", lbl_info);
		add("South", txt);

		setSize(300, 300);
		setVisible(true);

	}

	public static void main(String[] args) {
		new TextEvent_1("TextEvent Test~");
	}

	@Override
	public void textValueChanged(TextEvent e) {

		lbl_info.setText(txt.getText()); // txt 에 있는 문자를 가져다가 lbl_info에 적겠다. 

	}

}

 

 

 

 

 

 

 

 

 

 

 

package ja_0808;

import java.awt.Frame;
import java.awt.Label;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.TextEvent;
import java.awt.event.TextListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class TextEvent_2 extends Frame {

	TextField txt;
	TextArea txt_area;

	public TextEvent_2(String title) {
		super(title);

		addWindowListener(new Handler_2());

		txt_area = new TextArea();
		txt = new TextField("", 20);

		// 글자 입력 : 텍스트이벤트 , 엔터키를 누른다 : 액션 이벤트 
		txt.addTextListener(new Handler());
		txt.addActionListener(new Handler());

		txt_area.setFocusable(false); // 접근불가 
		txt_area.setEditable(false);  // 직접 글을 쓰거나 편집하지 못하도록 false를 줌 

		add("North", new Label("글자를 입력하고 Enter"));
		add("Center", txt_area);
		add("South", txt);

		setSize(300, 200);
		setVisible(true);

	}

	public static void main(String[] args) {
		new TextEvent_2("Test ~~");

	}

	class Handler_2 extends WindowAdapter { // 프레임에 달아줌 

		public void windowClosing(WindowEvent e) { // x를 누르면 실행되는 메소드 
			System.out.println("윈도우 닫기"); //콘솔에 출력
			System.exit(0); // 프로그램 종료
		}

	}

	class Handler implements ActionListener, TextListener { // 글자 입력 : 텍스트이벤트 , 엔터키를 누른다 : 액션 이벤트 

		@Override
		public void textValueChanged(TextEvent e) { // 글을쓰면 실행

			try {
				int i = txt.getText().length();
				if (i == 0) {
					return;
				}
				txt_area.append(" " + txt.getText().charAt(i - 1)); // 글자를 하나 하나 칠때마다 한개씩 호출됨 
			} catch (Exception e2) {
				System.out.println(e2.getMessage());
			}

		}

		@Override
		public void actionPerformed(ActionEvent e) { // 엔터 누르면 실행 
			txt.setText(""); // 엔터를 치면 txt를 빈칸 ""으로 바꿔줌 
			txt_area.append("\n");//엔터를 치면 텍스트 필드를 한칸 줄바꿈함 (개행)
		}

	}

}

텍스트칸에 글을 적으면 TextArea에 출력된다. 

try{ } 구문에서 한글자를 txt에적으면 getText().charAt(i-1)해서 그 한글자를 가져와서 Area에 append 해준다. 

그렇게 한개한개씩 받아서 Area에 적어줌 

엔터를 누르면 액션 퍼폼에 의해 Area는 줄바꿈이 일어나고 txt창은 비게된다.