이벤트
이벤트(Event)란 윈도우 시스템에서 일어나는 모든 사건들을 뜻하는 용어이다.
자바에서는 이러한 이벤트를 처리하기 위해 java.awt.event 패키지에 정의하고 있다.
또한 자바에서는 이런한 이벤트를 객체를 통해 전달하고 반응한다.
1. 자바 이벤트의 종류
1) 저수준 이벤트(AWT 컴포넌트에서 일어나는 이벤트)
이벤트 클래스
|
내용
|
(1) WindowEvent
|
윈도우가 활성화, 또는 닫힐 때 발생.
|
(2) ComponentEvent
|
컴퍼넌트의 추가/삭제에 의해 컨테이너의 내용이 변경되었을대
발생. |
(3) ContainerEvent
|
컨테이너에 컴포넌트가 추가/삭제되는 경우 발생.
|
(4) HierarchyEvent
|
컴포넌트의 계층구조가 바뀔 때 발생.
|
(5)
MouseEvent
|
마우스의 움직임에 의해 발생.
|
(6) MouseWheelEvent
|
마우스 휠의 움직임에 의해 발생.
|
(7) KeyEvent
|
커보드의 입력에 의해 발생.
|
(8) InputMethodEvnet
|
입력할 수 있는 멤소드에서 이벤트가 발생했을 때.
|
(9)
FocusEvent
|
컴포넌트에 포거스가 되었을 때.
|
(10) InputEvent
|
거의 모든 입력에 대한 이벤트가 발생했을때.
|
(11) PaintEvent
|
컴포넌트가 그려질 때 발생.
|
2) 고수준 이벤트(사용자의 반응에 의해 일어나는 이벤트)
(1) ActionEvent
|
버튼 클릭등의 동작
|
(2) AdjustmentEvent
|
스크롤바등의 위치가 바뀌었을때
|
(3) TextEvent
|
텍스트 내용이 바뀌었을때
|
(4) ItemEvent
|
항목의 상태가 바뀌었을때
|
2. Event를 처리하기 위한 절차

3. 컴포넌트와 이벤트의 종류
컴포넌트
|
발생 이벤트
|
Adju
|
Acti
|
Cont
|
Focu
|
Key
|
Mous
|
Comp
|
Item
|
Wind
|
Text
|
1.Adjustable
|
○
|
|
|
|
|
|
|
|
|
|
2. Applet
|
|
|
○
|
○
|
○
|
○
|
○
|
|
|
|
3. Button
|
|
○
|
|
○
|
○
|
○
|
○
|
|
|
|
4. Canvas
|
|
|
|
○
|
○
|
○
|
○
|
|
|
|
5. Checkbox
|
|
|
|
○
|
○
|
○
|
○
|
○
|
|
|
6. CheckboxMenuItem
|
|
○
|
|
|
|
|
|
○
|
|
|
7. Choice
|
|
|
|
○
|
○
|
○
|
○
|
○
|
|
|
8. Component
|
|
|
|
○
|
○
|
○
|
○
|
|
|
|
9. Container
|
|
|
○
|
○
|
○
|
○
|
○
|
|
|
|
10. Dialog
|
|
|
○
|
○
|
○
|
○
|
○
|
|
○
|
|
11. FileDialog
|
|
|
○
|
○
|
○
|
○
|
○
|
|
○
|
|
12. Frame
|
|
|
○
|
○
|
○
|
○
|
○
|
|
○
|
|
13. Label
|
|
|
|
○
|
○
|
○
|
○
|
|
|
|
14. List
|
|
○
|
|
○
|
○
|
○
|
○
|
○
|
|
|
15. Menu
|
|
○
|
|
|
|
|
|
|
|
|
16. MenuItem
|
|
○
|
|
|
|
|
|
|
|
|
17. Panel
|
|
|
○
|
○
|
○
|
○
|
○
|
|
|
|
18. PopupMenu
|
|
○
|
|
|
|
|
|
|
|
|
19. Scrollbar
|
○
|
|
|
○
|
○
|
○
|
○
|
|
|
|
20. ScrollPane
|
|
|
○
|
○
|
○
|
○
|
○
|
|
|
|
컴포넌트
|
발생 이벤트
|
Adju
|
Acti
|
Cont
|
Focu
|
Key
|
Mous
|
Comp
|
Item
|
Wind
|
Text
|
21. TextArea
|
|
|
|
○
|
○
|
○
|
○
|
|
|
○
|
22. TextComponent
|
|
|
|
○
|
○
|
○
|
○
|
|
|
○
|
23. TextField
|
|
○
|
|
○
|
○
|
○
|
○
|
|
|
○
|
24. Window
|
|
|
○
|
○
|
○
|
○
|
○
|
|
○
|
|
비고)
Adju : AdjustmentEvent
|
Acti : ActionEvnet
|
Cont : ContainerEvnet
|
Focu : FocusEvent
|
Key : KeyEvent
|
Mous : MouseEvent
|
Comp : ComponentEvent
|
item : ItemEvent
|
Wind : WindowEvent
|
Text : TextEvent
|
4. 이벤트 핸들러의 종류
1) Listener 2) Adapter : Listener 클래스를 부모 클래스로하여 파생되었으며
Listener에서 불필요하게 기술되던 메소드들을 추상으로 정의하고 있기 때문에 Adapter
핸들러 방식에서는 불필요한 메소드를 기술하지 않아도 되도록 만들어졌다.
5. 이벤트와 이벤트 핸들러
대부분의 이벤트 핸들러는 이벤트 이름의 "Event"란 단어 대신에 "Listener"
또는 "Adapter"를 붙여 이벤트에 대한 이벤트 핸들러명으로 사용한다.
예를 들어 MouseEvent라면 핸들러는 MouseListener와 MouseAdapter가 있다.
Listener or Adapter
|
구현해야 할 메소드
|
ActionListener
|
actionPerformed(ActionEvent e)
|
AdjustmentListener
|
adjustmentValueChange(AdjustmentEvent e)
|
ComponentListener ComponentAdapter
|
componentHidden(ComponentEvent e) componentShown(ComponentEvent
e) componentMoved(ComponentEvent e) componentResized(ComponentEvent
e)
|
ContainerListener ContainerAdapter
|
componentAdded(ContainerEvent e) componentRemoved(ContainerEvent
e)
|
FocusListener FocosAdapter
|
focusGained(FocusEvent e) focusLost(FocusEvent e)
|
ItemListener
|
itemStateChanged(ItemEvent e)
|
KeyListener KeyAdapter
|
keyPressed(KeyEvent e) keyReleased(KeyEvent e) keyTyped(KeyEvent
e)
|
MouseListener MouseAdapter
|
mouseClicked(MouseEvent e) mouseEntered(MouseEvent e) mouseExited(MouseEvent
e) mousePressed(MouseEvent e) mouseReleased(MouseEvent e)
|
MouseMotionListener MouseMotionAdapter
|
mouseDragged(MouseEvent e) mouseMoved(MouseEvent e)
|
WindowListener WindowAdapter
|
windowOpened(WindowEvent e) windowClosing(WindowEvent e) windowClosed(WindowEvent
e) windowActivated(WindowEvent e) windowDeactivated(WindowEvent
e) windowIconfied(WindowEvent e) windowDeiconfied(WindowEvent
e)
|
6. 이벤트별 메소드
1) ActionListener
(1) 주요 메소드
void actionPerformed(ActionEvent e)
|
반드시 구현해야 하며 이곳에서 이벤트에 대한 처리를 한다.
|
Object event_obj.getSource()
|
이벤트가 발생한 객체를 반환한다.
|
String event_obj.getActionCommand()
|
이벤트가 발생한 객체의 이름을 반환한다.
|
(2) 사용절차
가) class에 인터페이스를 추가한다.
public class ActionListenerEx implements ActionListener
나) 이벤트를 발생시킬 객체에 리스너를 추가한다.
Button b=new Button("Event Test Button"); b.addActionListener(this);
// this는 객체가 포함된 최 상위 윈도우 객체임.
다) ActionListener에서 필수로 구현해야할 actionPerformed() 메소드를 구현한다.
public void actionPerformed(ActionEvent e){ ... }
(3) 사용예
// ================================================================
// ActionListener Example
// make : pwg
// date : 2003
// note : 버튼을 클릭하거나, 리스트창에서 더블클릭하면
// 이벤트가 발생하여
텍스트 창에 내용이 표시된다.
// ----------------------------------------------------------------
// ActionEvent를 사용할 수 있는 컴포넌트
// Button, List, TextField, MenuItem, CheckboxMenuItem
// ================================================================
import java.awt.*;
import java.awt.event.*; // 필수
public class ActionListenerEx extends Frame implements
ActionListener
{
Button exitButton,cancelButton;
List list;
TextArea text;
Panel panelA,
panelB;
public ActionListenerEx()
{
setTitle("ActionListener");
panelA
= new Panel(new FlowLayout(FlowLayout.LEFT,0,0));
panelB
= new Panel(new GridLayout(2,1));
//
panelA
exitButton
= new Button("exit");
cancelButton
= new Button("cancel");
panelA.add(exitButton);
panelA.add(cancelButton);
//
panelB
list
= new List(10);
text
= new TextArea(5,40);
//
list item
list.add("호랑이");
list.add("고양이");
list.add("강아지");
list.add("망아지");
list.add("새앙쥐");
//
panelB.add(list);
panelB.add(text);
//
Event 추가
exitButton.addActionListener(this);
cancelButton.addActionListener(this);
list.addActionListener(this);
//
add(panelA,BorderLayout.NORTH);
add(panelB,BorderLayout.CENTER);
}
public static
void main(String args[])
{
ActionListenerEx
f=new ActionListenerEx();
f.setSize(500,300);
f.setVisible(true);
}
public
void actionPerformed(ActionEvent e) // ActionListener 에서는 반드시
구현
{
int
i;
if(e.getSource()
== exitButton)
{
dispose();
System.exit(0);
}
if(e.getSource()
== cancelButton)
{
text.setText("cancel");
}
if(e.getSource()
== list)
{
i
= list.getSelectedIndex();
text.append("list
-> " + e.getActionCommand());
text.append("
, Index ->" + i);
}
text.append("\n");
validate();
}
}
|
2) MouseListener / MouseMotionListener
(1) MouseListener 주요 메소드
void mouseClicked(MouseEvent e)
|
마우스가 클릭되었을때
|
void mouseEntered(MouseEvent e)
|
마우스가 컴포넌트 내로 들어왔을때
|
void mouseExited(MouseEvent e)
|
마우스가 컴포넌트 밖으로 나갔을때
|
void mousePressed(MouseEvent e)
|
마우스의 버튼이 눌렀을 때.mouseClicked()보다 먼저 발생됨.
|
void mouseReleased(MouseEvent e)
|
마우스 버튼을 놨을때
|
(2) MouseMotionListener 주요 메소드
void mouseDragged(MouseEvent e)
|
마우스를 드래그 할때
|
void mouseMoved(MouseEvent e)
|
마우스를 이동했을때
|
(2) 사용절차
가) class에 MouseListener 와 MouseMotionListener 인터페이스를 추가한다.
public class MouseListenerEx implements MouseListener,
MouseMotionListener
나) 이벤트를 발생시킬 객체에 리스너를 추가한다.
Button b=new Button("Event Test Button"); b.addMouseListener(this);
// this는 객체가 포함된 최 상위 윈도우 객체임.
다) MouseListener와 MouseMotionListener에서 필수로 구현해야할 메소드를 구현한다.
public void mouseClicked(MouseEvent e){ ... } public
void mousePressed(MouseEvent e({ ... } ...
(3) 사용예
// =====================================================
// MouseEvent Example
// make : pwg
// date : 2003
// note : 프레임이나 객체에서 마우스를 조작하면 이벤트가
// 발생하여 리스트창에
내용이 표시된다.
// =====================================================
import java.awt.*;
import java.awt.event.*;
public class MouseEventEx extends Frame implements
MouseListener,MouseMotionListener
{
Button exitButton,
testButton,moveButton;
TextArea text;
Panel topPanel;
int bx=0, by=0;
// 마우스 좌표.
public MouseEventEx()
{
topPanel
= new Panel(null);
topPanel.addMouseMotionListener(this);
topPanel.setBounds(0,30,100,25);
text
= new TextArea();
exitButton
= new Button("exit");
testButton
= new Button("test");
moveButton
= new Button("move");
exitButton.setBounds(0,0,30,20);
testButton.setBounds(30,0,30,20);
moveButton.setBounds(60,0,30,20);
//
add
topPanel.add(exitButton);
topPanel.add(testButton);
topPanel.add(moveButton);
//
Listener
exitButton.addMouseListener(this);
testButton.addMouseListener(this);
moveButton.addMouseListener(this);
topPanel.addMouseMotionListener(this);
add(topPanel,BorderLayout.NORTH);
add(text,BorderLayout.CENTER);
}
//
MouseListener Method
public void mouseClicked(MouseEvent
e)
{
text.append("mouseClicked...");
text.append("x="
+ e.getX());
text.append(",
y=" + e.getY());
text.append(",
Source=" + e.getSource());
text.append(",
Key =" + e.getModifiers());
text.append("\n");
validate();
bx=e.getX();
by=e.getY();
if(e.getSource()==exitButton)
System.exit(0);
}
public void mousePressed(MouseEvent
e)
{
text.append("mousePressed...\n");
validate();
}
public void mouseEntered(MouseEvent
e)
{
text.append("mouseEntered...\n");
validate();
}
public void mouseExited(MouseEvent
e)
{
text.append("mouseExited...\n");
validate();
}
public void mouseReleased(MouseEvent
e)
{
text.append("mouseReleased..."
+ e.getSource() + "\n");
validate();
}
public void mouseDragged(MouseEvent
e)
{
text.append("mouse
Dragged ...\n");
validate();
}
public void mouseMoved(MouseEvent
e)
{
bx=e.getX();
by=e.getY();
text.append("mouse
Moved ..." + bx + " , " + by + "\n");
validate();
}
public static
void main(String[] args)
{
MouseEventEx
f=new MouseEventEx();
f.setSize(600,300);
f.setVisible(true);
}
}
|
3) AdjustmentListener
(1) 필수 메소드
void adjustmentValueChange(AdjustmentEvent e)
|
AdjustmentEvent가 발생되면 call되는 필수 메소드
|
(2) 주요 메소드
int e.getValue()
|
객체의 현재 값을 리턴
|
(3) 사용절차
가) class에 인터페이스를 추가한다.
public class AdjustmentListenerEx implements AdjustmentListener
나) 이벤트를 발생시킬 객체에 리스너를 추가한다.
Scrollbar rScrollbar = new Scrollbar(); sScrollbar.addAdjustmentListener(this);
다) 필수로 구현해야하는 메소드를 구현하고 메소드안에 이벤트에 해당하는 처리
내용을 기술한다.
public adjustmentValueChange(AdjustmentEvent e) { ... }
(4) 사용예
// ==============================================================
// AdjustmentListener Example
// make : pwg
// date : 2003
// --------------------------------------------------------------
// note : 스크롤바를 드래그하여 패널의 색상을 바꾼다.
// ==============================================================
import java.awt.*;
import java.awt.event.*;
public class AdjustmentListenerEx extends Frame implements
ActionListener, AdjustmentListener
{
Panel pCenter,
pEast;
Scrollbar rScrollbar,
gScrollbar, bScrollbar;
Button exitButton;
int r=100,g=100,b=100;
public AdjustmentListenerEx()
{
//
panel
pCenter
= new Panel();
pEast
= new Panel(new GridLayout(0,3));
//
component
rScrollbar
= new Scrollbar(Scrollbar.VERTICAL, 100,50,0,305);
gScrollbar
= new Scrollbar(Scrollbar.VERTICAL, 100,50,0,305);
bScrollbar
= new Scrollbar(Scrollbar.VERTICAL, 100,50,0,305);
rScrollbar.setBackground(new
Color(255,0,0));
gScrollbar.setBackground(new
Color(0,255,0));
bScrollbar.setBackground(new
Color(0,0,255));
exitButton
= new Button("exit");
//
Listener
exitButton.addActionListener(this);
rScrollbar.addAdjustmentListener(this);
gScrollbar.addAdjustmentListener(this);
bScrollbar.addAdjustmentListener(this);
pCenter.setBackground(new
Color(r,g,b));
pEast.add(rScrollbar);
pEast.add(gScrollbar);
pEast.add(bScrollbar);
add(pCenter,
BorderLayout.CENTER);
add(pEast,BorderLayout.EAST);
add(exitButton,
BorderLayout.NORTH);
}
//
Listener Method
public void actionPerformed(ActionEvent
e)
{
dispose();
System.exit(0);
}
public void adjustmentValueChanged(AdjustmentEvent
e)
{
if(e.getSource()
== rScrollbar) r=e.getValue();
if(e.getSource()
== gScrollbar) g=e.getValue();
if(e.getSource()
== bScrollbar) b=e.getValue();
pCenter.setBackground(new
Color(r,g,b));
validate();
}
public static
void main(String[] args)
{
AdjustmentListenerEx
f= new AdjustmentListenerEx();
f.setSize(300,300);
f.setVisible(true);
}
}
|
4) KeyListener
(1) 필수 메소드
void keyPressde(KeyEvent e)
|
키가 눌려지면 발생.
|
void keyReleased(KeyEvent e)
|
눌려진 키가 띄어지면 발생.
|
void KeyTyped(KeyEvent e)
|
타자되면 발생.
|
(2) 주요 메소드
char getKeyChar()
|
입력된 문자
|
int getKeyCode()
|
입려된 문자의 상수값.(상수값은 내정되어 있음)
|
(3) 주요 상수값
VK_ENTER
|
|
VK_UP
|
|
VK_ALT
|
|
VK_DOWN
|
|
VK_CONTROL
|
|
VK_LEFT
|
|
VK_SHIFT
|
|
VK_RIGHT
|
|
(4) 사용예
// ==============================================
// KeyListener Example
// make : pwg
// date : 2003
// ----------------------------------------------
// note : 키가 눌려지면 해당 키의 내용이
// 리스트창에 표시된다.
// ==============================================
import java.awt.*;
import java.awt.event.*;
public class KeyListenerEx extends Frame implements ActionListener,
KeyListener
{
Panel topPanel;
Button exitButton;
TextArea textArea;
TextField textField;
public KeyListenerEx()
{
Panel
topPanel = new Panel();
exitButton
= new Button("Exit");
textArea
= new TextArea(10,30);
textField
= new TextField(20);
//
add_on Panel
topPanel.add(textField);
topPanel.add(exitButton);
add(textArea,BorderLayout.CENTER);
add(topPanel,BorderLayout.NORTH);
//
add Listener
textField.addKeyListener(this);
exitButton.addActionListener(this);
}
public void actionPerformed(ActionEvent
e)
{
System.exit(0);
}
public void keyTyped(KeyEvent
e)
{
textArea.append(""
+ e.getKeyChar() + "\n");
}
public void keyPressed(KeyEvent
e)
{
if(e.getKeyCode()
== KeyEvent.VK_ENTER)
{
textArea.append(textField.getText()
+ "\n");
textField.setText("");
}
if(e.getKeyCode()
== KeyEvent.VK_ALT)
{
textArea.append("
alt key in \n");
}
if(e.getKeyCode()
== KeyEvent.VK_CONTROL)
{
textArea.append("
control key in \n");
}
}
public void keyReleased(KeyEvent
e)
{
}
public static
void main(String[] args)
{
KeyListenerEx
f= new KeyListenerEx();
f.setSize(500,300);
f.setVisible(true);
}
}
|
5) WindowListener
(1) 필수 메소드
void windowOpend(WindowEvent e)
|
창이 열렸을때
|
void windowClosing(WindowEvent e)
|
창이 닫히고 있을때
|
void windowClosed(WindowEvent e)
|
창이 닫혔을때
|
void windowActivated(WidnowEvent e)
|
활성화 되었을때
|
void windowDeactivated(WindowEvent e)
|
비활성화 되었을때
|
void windowIconified(WidnowEvent e)
|
최소화 되었을때
|
void windowDeiconified(WindowEvent e)
|
창이 다시 복귀되었을때
|
(2) 사용예
// ============================================
// WindowListener Example
// make : pwg
// date : 2003
// --------------------------------------------
// note :
// ============================================
import java.awt.*;
import java.awt.event.*;
public class WindowListenerEx extends Frame implements WindowListener,
ActionListener
{
Button exitButton;
public WindowListenerEx()
{
exitButton
= new Button("exit");
add(exitButton);
exitButton.addActionListener(this);
addWindowListener(this);
}
public void actionPerformed(ActionEvent
e)
{
System.exit(0);
}
// WindowListener
Method
public void windowActivated(WindowEvent
e)
{
System.out.println("Window
Active");
}
public void windowClosed(WindowEvent
e)
{
System.out.println("Window
Closed");
}
public void windowClosing(WindowEvent
e)
{
System.out.println("Window
Closing");
dispose();
System.exit(0);
}
public void windowDeactivated(WindowEvent
e)
{
System.out.println("Window
Deactive");
}
public void windowIconified(WindowEvent
e)
{
System.out.println("Window
Icon");
}
public void windowDeiconified(WindowEvent
e)
{
System.out.println("Window
Deicon");
}
public void windowOpened(WindowEvent
e)
{
System.out.println("Window
Open");
}
public static
void main(String[] args)
{
WindowListenerEx
f= new WindowListenerEx();
f.setSize(300,300);
f.setVisible(true);
}
}
|
7. Adapter
이벤트를 처리하기 위해 이벤트 핸들러인 Listener를 사요하였다. Listener의
단점은 메소드를 사용하던 사요하지 않던 모든 메소드를 기술해야 된다는 점이다.
WindowListener를 생각해 보자.
가장 많이 사용하는 메소드가 windowClosed()이다. 창을 닫기 위해 사용하는 메소드이지만
이 메소드를 사용하기 위해 WindowListener를 사용하였다면 사용하지 않는 다른 6가지의
메소드를 모두 기술해 주어야 한다.
이런 불편한점을 개선하여 자바는 Adapter라는 이벤트 핸들러들 만들어 두었다.
1) 사용 절차
Listener 핸들러에서는 사용하려는 Listener를 implements로 상속받아 사용하는
것이 보편적인 방법이라면, Adapter는 해당 Adapter를 extends로 상속받아 내부 클래스를
만들어 사용하는 것이 보편적인 방법이다.
내부 클래스로 만들어 사용하면 외부 클래스를 만들어 사용할 때 보다 좋은점은
각 컴포넌트나 변수들을 접근하여 처리하기 쉽기 때문이다.
(1) 내부 클래스로 만들어진 클래스 객체를 인수로 하는 Listener를 이벤트 대상에
더한다.
Button exitButton=new Button("Exit"); exitButton.addMouseListener(new
MyMouseAdapter()); // MyMouseAdater()는 내부 이벤트 클래스
(2) 내부 클래스를 해당 이벤트에 대한 Adapter를 상속받아 작성한다.
class MyMouseAdapter extends MouseAdapter { public
void mouseClicked(MouseEvent e) { .....
} }
2) 사용예
// ===============================================
// WindowAdapter Example
// make : pwg
// date : 2003
// note :
// ===============================================
import java.awt.*;
import java.awt.event.*;
public class WindowAdapterEx extends Frame
{
Button b;
public WindowAdapterEx()
{
addWindowListener(new
myWinAdapter());
b=new
Button("exit");
b.addMouseListener(new
myMouseAdapter());
add(b);
}
public static void main(String[]
args)
{
WindowAdapterEx
f= new WindowAdapterEx();
f.setSize(300,300);
f.setVisible(true);
}
// 내부 클래스
class
myWinAdapter extends WindowAdapter
{
public
void windowClosing(WindowEvent e)
{
String
str=b.getLabel();
System.out.println("window
closed event...");
System.out.println(str
+ "버튼도 있는데...");
System.exit(0);
}
}
class
myMouseAdapter extends MouseAdapter
{
public
void mouseClicked(MouseEvent e)
{
System.out.println("windowClosing
도 있는데...");
System.exit(0);
}
};
}
|
|