Event ( 이벤트 )
이벤트는 GUI( Graphical User Interface ) 프로그램에서 가장 중요한 개념으로 사용자가 입력 장치(키보드,마우스 등)를 이용해 발생하는 사건을 말한다. 이벤트를 처리하는 GUI 프로그램은 이벤트가 발생할때까지 무한 루프를 돌면서 대기상태에 있게 된다. 이런 상태에서 이벤트가 발생하면 그 이벤트에 따라 특정 작업을 수행한다.
이벤트와 관련된 기능은 GUI 운영체제에서 지원되는 이벤트 처리를 기본으로 하는 프로그램 작성 방법을 이벤트지항(Event - driven) 프로그램 기법이라고 한다.
자바에서 이벤트 관련 프로그램을 작성하기 위해 java.awt.event.* 패키지를 제공하고 위임형 이벤트모델(Delegation Event Model)을 사용해 이벤트를 처리한다.
event handling(이벤트 핸들링)
: 이벤트란 사용자 또는 프로그램 코드에 의해 발행 할 수 있는 사건을 말한다.
예를들어 사용자가 마우스를 움직이거나, 키보드를 눌렀을때 또는 Frame의 크기를 변경할때 이벤트가 발생한다.
Event Source | 이벤트가 발생한 컴포넌트, 사용자가 버튼을 눌렀을때 이벤트가 발생하고 버튼은 이 이벤트 소스가된다. |
Event Handler | 이벤트가 발생했을때 실행될 코드를 구현해 놓은 클래스 |
Event Listener | 이벤트를 감지하고 처리한다. 이벤트 핸들러를 이벤트 리스너로 이벤트소스에 연결해야 이벤트가 발생했을때 이벤트가 처리된다. |
이벤트에 대한 수행코드를 작성하여 이벤트 소스에 이벤트리스너로 등록되는 것을 이벤트처리(event handeler)라고 한다.
이벤트가 발생하더라도 그에 대한 이벤트 처리를 하지 않으면, 아무일도 일어나지 않는다.
사용자가 AWT 프로그램을 사용하면서 행하는 모든 동작은 이벤트를 발생시킨다.
하지만 그에 대한 이벤트를 처리하지 않아 이벤트가 발생한 사실을 사용자가 알지 못한다.
이벤트 관련 컴포넌트
컴포넌트와 이벤트 : 컴포넌트에 따라 발생 가능한 이벤트가 달라진다.
이벤트의 종류
ActionEvent | 버튼클랙, 리스트항목의 더블클릭, 메뉴항목의 선택, 택스트 필드에서 엔터키 눌렀을때 |
AdjustmentEvent | 사용자가 스크롤바를 움직였을때 발생 |
CompomentEvent | 컴포넌트가 사라지거나 나타날때, 컴포넌트의 이동 및 크기조절시에 발생 |
FocusEvent | 컴포넌트가 초점을 얻거나 잃었을때 발생 |
ItemEvent | 체크박스, 선택버튼, 리스트의 한 항목이 선택되었을때 메뉴의 항목이 선택되거나 해지될떄 발생 |
KeyEvent | 키보드로 부터 입력이 발생할때 발생 |
MouseEvent | 마우스 버튼을 클릭할때, 누를때, 놓을때, 컴포넌트 영역에 들어갈떄, 나올때 발생 |
MouseMotionEvent | 마우스 드래그와 이동시 발생 |
TextEvent | TextArea,TextField 에서 값이 입력 될 때 발생 |
WindowEvent | 윈도우가 활성화(Activate), 비활성화, 아이콘화, 아이콘에서 복귀될때 , 윈도우 오픈, 종료시 발생 |
이벤트 처리방법
: 컴포넌트 객체에서 이벤트가 발생하면 컴포넌트는 이벤트 소스가 되고 이벤트 리스너가 이벤트를 처리하도록 해야한다.
자바는 이벤트 리스너를 만들기 위해 인터페이스를 사용한다. 각이벤트에 따라 등록해야 하는 인터페이스가 있고 이를 Listener라 한다. 이러한 인터페이스들은 "이벤트이름 + Listener"형태로 되어있다.
ActionListener, MouseListener등이 있다.
이벤트 리스너는 이벤트와 관련된 인터페이스를 상속받아 구현해야 한다.
순서
1. java.awt 와 java.awt.event 패키지를 import 한다.
java.awt.* ;
java.awt.event.* ;
2.리스너 인터페이스를 상속받아 이벤트 리스너를 구현한다.
이때 인터페이스에 있는 메소드를 재정의 한다.
class Event extends Frame implements ActionListener
{
public void actionPerformed ( ActionEvent e )
{
.......;
}
}
3. AWT 컴포넌트를 생성한다.
Button btn = new Button("버튼") ;
4. 컴포넌트 종류에 따라 해당 리스너 객체를 등록한다.
btn.addActionListener(this);
btn에 액션이 발생하면 addActionListener가 그걸 캐치해서 this로 전달함
this 는 여기서addActionListener이고 이안에서 해당 액선에 대한 메소드로 이동한다
🟢 ActionListener
package ja_0804;
import java.awt.Button;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Event_1 extends Frame implements ActionListener {
public Event_1(String title) {
super(title);
Button btn = new Button("버튼 ~");
btn.addActionListener(this); // this : ActionListner을 가진 class를 의미함
add(btn);
setSize(300, 300);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) { //버튼을 누를때 마다 실행되는 것들
System.out.println("*********이벤트 발생 정보***********");
System.out.println("e.getSource() Method : " + e.getSource());
System.out.println("e.toString() : " + e.toString());
System.out.println("e.getID() : " + e.getID());
System.out.println("e.paramString() : " + e.paramString());
System.out.println("**********************************");
}
public static void main(String[] args) {
new Event_1("Event Test~~");
}
}
package ja_0805;
import java.awt.Button;
import java.awt.Frame;
import java.awt.Label;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ActionEvent_1 extends Frame implements ActionListener {
Label lbl_info;
Button btn1, btn2,btn3;
public ActionEvent_1(String str) {
super(str);
lbl_info = new Label("버튼을 누르세요");
btn1 = new Button("◀ Button");
btn2 = new Button("▶ Button");
btn3 = new Button("● Button");
btn3.addActionListener(this);
btn1.addActionListener(this); //이벤트를 달아둠
btn2.addActionListener(this);//버튼에서 이벤트가 발생하면 처리하겠다는 의미
//this는 자기자신이 그 처리방법을 가지고 있다는 말
Panel panel = new Panel();
panel.add(btn1);
panel.add(btn3);
panel.add(btn2);
add("Center", panel);
add("South", lbl_info);
setSize(300, 200);
setVisible(true);
}
public static void main(String[] args) {
new ActionEvent_1("ActionEvent Test~");
}
@Override
public void actionPerformed(ActionEvent e) { //this가 의미하는 것
Object obj = e.getSource(); //이벤트가 처음 발생한 객체(버튼), 리턴타입이 Object이므로 오브젝트에 담음
if ((Button) obj == btn1) {
lbl_info.setText("왼쪽 버튼이 눌렸습니다.");
} else if((Button)obj ==btn2) {
lbl_info.setText("오른쪽 버튼이 눌렸습니다.");
}else {
lbl_info.setText("가운데 버튼이 눌렸습니다.");
}
}
}
이벤트를 처리할 구문이 같은 class 내부에 존재하면 this로 호출함.
package ja_0805;
import java.awt.Button;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ActionEvent_2 extends Frame implements ActionListener {
TextArea txt_info;
Button btn1, btn2, btn3;
public ActionEvent_2(String title) {
super(title);
txt_info = new TextArea("--버튼을 눌러주세요--\n");
btn1 = new Button("< 버튼");
btn2 = new Button("> 버튼");
btn3 = new Button("$ 버튼");
btn1.addActionListener(this);
btn3.addActionListener(this);
btn2.addActionListener(this);
Panel panel = new Panel();
panel.add(btn1);
panel.add(btn3);
panel.add(btn2);
add("Center", txt_info);
add("South", panel);
setSize(300, 200);
setVisible(true);
}
public static void main(String[] args) {
new ActionEvent_2("Test");
}
@Override
public void actionPerformed(ActionEvent e) {
txt_info.append(e.getActionCommand() + "눌렸습니다.\n");
System.out.println(e.getActionCommand() + "눌렸습니다.");
// e.getActionCommand() : 버튼에 적혀있는 Command, 버튼에 적은 이름을 말함
}
}
(버튼을 클릭하여 패널의 색상 순환시키기)
package Test;
import java.awt.Button;
import java.awt.Color;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class anser extends Frame implements ActionListener {
Label lbl_info;
Button[] btn = new Button[9];
Color[] color = { Color.red, Color.orange, Color.yellow, Color.green, Color.magenta, Color.cyan, Color.gray,
new Color(215, 188, 242), new Color(163, 245, 182) };
String[] string = { "Red", "Orange", "Yellow", "Green", "Magenta", "Cyan", "Gray", "Puple", "ligtGreen" };
Panel p1, p2, p3, p4, p5;
public anser(String title) {
super(title);
// setLayout(new GridBagLayout());
p1 = new Panel(); // 버튼이 담길 공간
p2 = new Panel();// 색깔나올공간 1
p3 = new Panel(); // 색깔나올공간 2
p4 = new Panel(); // 색깔패드를 담을 공간
p5 = new Panel();// 색깔나올 공간3
p4.setLayout(new GridLayout(1, 3));
for (int i = 0; i < 9; i++) {
btn[i] = new Button(string[i]);
btn[i].setForeground(color[i]); // 글자색 변경
btn[i].addActionListener(this); // 이벤트 달아줌
p1.add(btn[i]); // 프레임에 버튼 add
// 플로우 레이아웃이므로 버튼들이 좌에서 우로 배치된다.
}
p4.add(p2);
p4.add(p3);
p4.add(p5);
add("North", p1);
add("Center", p4);
setSize(300, 200);
setVisible(true);
}
public static void main(String[] args) {
new anser("Test");
}
@Override
public void actionPerformed(ActionEvent e) { // 여기가 this
Button obj = (Button) e.getSource(); // 버튼으로 형변환 하여 받겠다.
// Object obj = e.getSource(); 오브젝트 타입 메소드이다
for (int i = 0; i < 9; i++) {
if (obj == btn[i]) {
p2.setBackground(color[i]);
p3.setBackground(color[(i + 1) % 9]);
p5.setBackground(color[(i + 2) % 9]);
}
}
System.out.println(e.getActionCommand() + "눌렀습니다.\n");
}
}
(예) TextArea에서의 활용 예시
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("Event Test~");
}
@Override
public void actionPerformed(ActionEvent e) { //글자를 치고 엔터를 누르면 이벤트 발생
TextField obj = (TextField) e.getSource();
if (obj == txt_1) {
txt_2.setText(txt_1.getText());
txt_3.setText(txt_1.getText()); // 1번에 입력한txt를 2,3에 가져다 넣겠다.
//getText() : 입력한 Txt가져옴
txt_2.setFocusable(true); //true문장은 항상 false문장보다 위에 있어야 한다. (선점해야함)
txt_1.setFocusable(false);
txt_3.setFocusable(false);
} else if (obj == txt_2) {
txt_1.setText(txt_2.getText());
txt_3.setText(txt_2.getText());
txt_3.setFocusable(true);
txt_1.setFocusable(false);
txt_2.setFocusable(false);
} else {
txt_1.setText(txt_3.getText());
txt_2.setText(txt_3.getText());
txt_1.setFocusable(true);
txt_2.setFocusable(false);
txt_3.setFocusable(false);
}
}
}
(예) List 에서의 예시
package ja_0805;
import java.awt.Frame;
import java.awt.Label;
import java.awt.List;
import java.awt.Panel;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ActionEvent_5 extends Frame implements ActionListener {
List list;
Label lbl_info;
TextArea lbl_info2;
Panel panel;
public ActionEvent_5(String title) {
super(title);
panel = new Panel();
list = new List(5, true);
list.add("서울");
list.add("대구");
list.add("대전");
list.add("부산");
list.add("광주");
list.add("전주");
list.add("울산");
list.add("인천");
list.add("제주");
panel.add(list);
lbl_info = new Label(" ");
lbl_info2 = new TextArea("~~~");
list.addActionListener(this);
add("Center", panel);
add("South", lbl_info2);
setSize(300, 300);
setVisible(true);
}
public static void main(String[] args) {
new ActionEvent_5("@@@Test~@@@");
}
@Override
public void actionPerformed(ActionEvent e) { // list에서 더블클릭하면 엑션이 작동한다
// TODO Auto-generated method stub
String[] list_1 = list.getSelectedItems();
for (int i = 0; i < list_1.length; i++) {
lbl_info2.append(list_1[i] + "찍고 ~ \n");
System.out.println(list_1[i] + "찍고 ~ \n");
}
}
}
(로그인창 만들기)
package ja_0805;
import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ActionEvent_6 extends Frame implements ActionListener {
Label lid;
Label lpwd;
Label lTel;
TextField tfId;
TextField tfPwd;
TextField tfTel;
Button ok;
public ActionEvent_6(String title) {
super(title);
lid = new Label("ID : ", Label.RIGHT);
lpwd = new Label("PWD : ", Label.RIGHT);
lTel = new Label("Tel : ", Label.RIGHT);
tfId = new TextField(10);
tfPwd = new TextField(10);
tfTel = new TextField(10);
tfPwd.setEchoChar('*');
ok = new Button("OK");
tfId.addActionListener(this);
tfPwd.addActionListener(this);
tfTel.addActionListener(this);
ok.addActionListener(this);
setLayout(new FlowLayout());
add(lid);
add(tfId);
add(lpwd);
add(tfPwd);
add(lTel);
add(tfTel);
add(ok);
setSize(450, 80);
setVisible(true);
}
public static void main(String[] args) {
new ActionEvent_6("Login Test");
}
@Override
public void actionPerformed(ActionEvent e) {// 엔터키를 치거나 ok를 누르거나 했을때 작동
// TODO Auto-generated method stub
String id = tfId.getText();
String password = tfPwd.getText();
String tel = tfTel.getText();
if (!id.equals("korea")) {
System.out.println("입력하신 ID가 존재하지 않습니다. 다시입력해주세요");
tfId.requestFocus(); // 포커스를 tfId로 가져다둠
tfId.selectAll(); // 모두 반전시켜라 (모두 선택해서 파랗게 블럭이 생김)
} else if (!password.equals("seoul")) {
System.out.println("입력하신 password가 존재하지 않습니다. 다시입력해주세요");
tfPwd.requestFocus();
tfPwd.selectAll();
} else if (!tel.equals("01012341234")) {
System.out.println("입력하신 전화번호가 존재하지 않습니다. 다시입력해주세요");
tfTel.requestFocus();
tfTel.selectAll();
} else {
System.out.println(id + "님 로그인 되었습니다.");
}
}
}
로그인 실패시 블럭이 반전되는 화면 |
![]() |
console 출력화면 | ![]() |
(포인트)
● if로 비교할때는 보통 아니라면(not)을 많이 사용한다.
id - pw - tel 순서로 맞는 것은 넘어가고 틀린것이 발생하면 if문이 바로 작동하는 것이다.
즉 id는 똑바로 쓰고 pwd을 잘못 썻다면 id는 if에서 걸리는 것이 없음으로 통과하고 fwd에서 틀린것이 있음으로 if문이
작동하는 것이다. 순서대로 작동함으로 pwd에서 걸렸으면 tel에관한 if문은 틀렷다 할지라도 작동하지 않는다.
● TextField, Button에 모두 액션 리스너를 달아주었음으로 TextField에 해당하는 엔터를 치거나 혹은 버튼을 눌렀을때 모두
actionPerformed( ) 가 작동한다.
(예) 계산기 만들기
package ja_0804;
import java.awt.Button;
import java.awt.Color;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Panel;
import java.awt.TextField;
public class Calc_1 {
public static void main(String[] args) {
Frame ff = new Frame("계산기");
TextField tf = new TextField("0");
tf.setEnabled(false); // 활성화가 안됨 글씨가 회색으로 나옴
ff.setSize(210, 180);
ff.setLocation(400, 300);
ff.add("North", tf);
Panel numPanel = new Panel();
Button[] numButtons = null;
numPanel.setLayout(new GridLayout(4, 5, 5, 5));//(행,열,좌우여백,상하여백)
numPanel.setBackground(Color.LIGHT_GRAY);
ff.add("Center", numPanel);
String[] numStr = { "7", "8", "9", "/", "CE",
"4","5", "6", "*", "BS",
"1", "2", "3", "-", "1/x",
"0", "+/-",".", "+", "=" };
numButtons = new Button[numStr.length]; //버튼을 생성
//문자열 numStr을 버튼에 담음
for (int i = 0; i < numStr.length; i++) {
numButtons[i] = new Button(numStr[i]);
numButtons[i].setForeground(Color.blue);
numPanel.add(numButtons[i]); // 버튼을 패널에 붙임
}
ff.setResizable(true); //true : 프레임사이즈 늘어나고 줄여들고 가능 false이면 사이즈고정됨
ff.setVisible(true);
}
}
🟢Window
package ja_0804;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Label;
import java.awt.Window;
public class Window_1 extends Frame {
int x = 0;
int y = 0;
Window[] win = new Window[40];
Color[] color = { Color.red, Color.yellow, Color.green };
public Window_1(String str) {
super(str);
for (int i = 0; i < 40; i++) {
win[i] = new Window(this);
win[i].setBackground(color[i % 3]);
// 3으로나눈 나머지는 0,1,2뿐이므로 color배열의 3개가 나옴
win[i].setVisible(true);
Label lbl = new Label(i + "번 윈도우");
win[i].add(lbl);
if ((i / 10) % 2 == 0) {
x += 10;
y += 10;
win[i].setBounds(100 + x, 100 + y, 100, 100);
} else {
x += 10;
y -= 10;
win[i].setBounds(100 + x, 100 + y, 100, 100);
}
}
setLocation(90, 90);
setVisible(true);
}
public static void main(String[] args) {
new Window_1("윈도우");
}
}
if ((i / 10) % 2 == 0) 이용한이유 : w모양을 반복할때 10개씩 끊어서 한획씩 만들고자함
즉 한번은 아래로 10개 한번은 위로 10개 올라가도록 반복하면 w모양이 만들어진다.
10개식 끊고자함 i/10은 10의자리수를 나타낸다 10의자리수가 홀수일때 내려가도록 만들고자함. 즉 (i/10)%2 한것이 0과 같다면 아래로 내려가고 else인 반대경우는 올라가도록 코드를 작성해 주었다.
<< 완성된 모습
(응용한 코드)
package ja_0804;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Label;
import java.awt.Window;
public class Window_1 extends Frame {
int x = 0;
int y = 0;
Window[] win = new Window[600];
Color[] color = { Color.red, Color.yellow, Color.green };
public Window_1(String str) {
super(str);
for (int i = 0; i < 600; i++) {
win[i] = new Window(this);
win[i].setBackground(color[i % 3]);
// 3으로나눈 나머지는 0,1,2뿐이므로 color배열의 3개가 나옴
win[i].setVisible(true);
Label lbl = new Label(i + "번 윈도우");
win[i].add(lbl);
if (i < 170) {
if ((i / 10) % 2 == 0) {
x += 10;
y += 10;
win[i].setBounds(100 + x, 100 + y, 100, 100);
} else {
x += 10;
y -= 10;
win[i].setBounds(100 + x, 100 + y, 100, 100);
}
}
if (i >= 170 && i < 250) {
if ((i / 10) % 2 == 0) {
x += 10;
y += 10;
win[i].setBounds(100 + x, 100 + y, 100, 100);
} else {
x -= 10;
y += 10;
win[i].setBounds(100 + x, 100 + y, 100, 100);
}
}
if (i >= 250 && i < 400) {
if ((i / 10) % 2 == 0) {
x -= 10;
y += 10;
win[i].setBounds(100 + x, 100 + y, 100, 100);
} else {
x -= 10;
y -= 10;
win[i].setBounds(100 + x, 100 + y, 100, 100);
}
}
if (i >= 400 && i < 600) {
if ((i / 10) % 2 == 0) {
x += 10;
y -= 10;
win[i].setBounds(100 + x, 100 + y, 100, 100);
} else {
x -= 10;
y -= 10;
win[i].setBounds(100 + x, 100 + y, 100, 100);
}
}
}
setLocation(90, 90);
setVisible(true);
}
public static void main(String[] args) {
new Window_1("윈도우");
}
}
이렇게 응용도 가능 !
package ja_0804;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Label;
import java.awt.Window;
public class Window_1 extends Frame {
int x = 0;
int y = 0;
Window[] win = new Window[560];
Color[] color = { Color.red, Color.yellow, Color.green };
public Window_1(String str) {
super(str);
for (int i = 0; i < 500; i++) {
win[i] = new Window(this);
win[i].setBackground(color[i % 3]);
// 3으로나눈 나머지는 0,1,2뿐이므로 color배열의 3개가 나옴
win[i].setVisible(true);
Label lbl = new Label(i + "번 윈도우");
win[i].add(lbl);
if (i < 170) {
if ((i / 10) % 2 == 0) {
x += 10;
y += 10;
win[i].setBounds(100 + x, 100 + y, 100, 100);
} else {
x += 10;
y -= 10;
win[i].setBounds(100 + x, 100 + y, 100, 100);
}
}
if (i >= 170 && i < 250) {
if ((i / 10) % 2 == 0) {
x += 10;
y += 10;
win[i].setBounds(100 + x, 100 + y, 100, 100);
} else {
x -= 10;
y += 10;
win[i].setBounds(100 + x, 100 + y, 100, 100);
}
}
if (i >= 250 && i < 420) {
if ((i / 10) % 2 == 0) {
x -= 10;
y += 10;
win[i].setBounds(100 + x, 100 + y, 100, 100);
} else {
x -= 10;
y -= 10;
win[i].setBounds(100 + x, 100 + y, 100, 100);
}
}
if (i >= 420 && i < 500) {
if ((i / 10) % 2 == 0) {
x += 10;
y -= 10;
win[i].setBounds(100 + x, 100 + y, 100, 100);
} else {
x -= 10;
y -= 10;
win[i].setBounds(100 + x, 100 + y, 100, 100);
}
}
}
setLocation(90, 90);
setVisible(true);
}
public static void main(String[] args) {
new Window_1("윈도우");
}
}
'KH > JAVA' 카테고리의 다른 글
# 45 Event -Scrollber, Mouse,Key,Window (0) | 2022.08.09 |
---|---|
# 44 AdjustmentEvent , ItemEvent (0) | 2022.08.05 |
# 42 Dialog (0) | 2022.08.04 |
# 41 Layout (0) | 2022.08.03 |
# 40 AWT(2) - TextField , Menu (0) | 2022.08.03 |