자바 Event 핸들러 KeyListener, KeyAdapter와 KeyEvent

자바 Event 핸들러 KeyListener, KeyAdapter와 KeyEvent


KeyListener, KeyAdapter와 KeyEvent


  • . Key타입의 Event는 인터페이스인 KeyListener와 클래스인 KeyAdapter를 가진다
  • . 메서드 (Method)
  • public void keyTyped(KeyEvent e){}
  • public void keyPressed(KeyEvent e){}
  • public void keyReleased(KeyEvent e){}
  • . Key Event는 키보드에서 아무키나 누를 때 혹은 뗄때 발생하는 Event이다 .
    따라서 사용자로 하여금 특정 키를 입력하지 못하도록 할 때에는 참 유용하다.

ex )

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import java.awt.*;
import java.awt.event.*;

class Round19_Ex04_Sub extends Frame implements KeyListener {// KeyListener를
// 인터페이스한다.
private FlowLayout fl = new FlowLayout();
private TextField tf = new TextField(10);
private Label lb = new Label("-", Label.CENTER);
private TextField tf1 = new TextField(10);

public Round19_Ex04_Sub() {
super("Test");
this.init();
this.start();
this.setSize(300, 200);
this.setVisible(true);
}

public void init() {
this.setLayout(fl);
this.add(tf);
this.add(lb);
this.add(tf1);
}

public void start() {
tf.addKeyListener(this);
// 자기자신의 KeyListener를 호출한다.
}

public void keyPressed(KeyEvent e) {
}

// 키가 눌렸을때 즉 키를 누르고 있을때 발생하는 이벤트
public void keyReleased(KeyEvent e) {
// 키를 뗏을때 즉 키를 누르고 뗏을때 발생하는 이벤트
String str = tf.getText().Trim();
// tf의 공백을 제거한 텍스트를 String에 담는다
if (str.length() == 6) {
// str의 길이가 6일때
tf1.requestFocus();
// tf1로 포커스를 이동한다
}
}

public voidkeyTyped(KeyEvent e) {
}
// 키를 누르고 뗏을때 즉 키를 누른다음 뗄떼 발생하는 이벤트 .
}

public class Round19_Ex04 (){
public static void main(String[] ar) {
Round19_Ex04_Sub es = new Round19_Ex04_Sub();
}
}

Share