Event와 관련 패키지들
닫기 버튼을 누르면 프로그램이 종료되는 예
import java.awt.*;
import java.awt.event.*;
public class Round19_Ex01 {
public static void main(String[] args) {
new Round19_Ex01_Sub();
}
class Round19_Ex01_Sub extends Frame {
....
private Button bt = new Button("닫기");
public Round19_Ex01_Sub() {
....
}
public void init() {
....
}
public void start() {
bt.addActionEventListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
}
}
}
- Event의 구성
- Listener interface
- Adapter class
- Event class
- 컴포넌트에 따른 적용 Event
- Frame : Focus, Key, Mouse, MouseMotion, Window
- Label : Focus, Key, Mouse, MouseMotion
- Button : Focus, Key, Mouse, MouseMotion, Action
- Checkbox : Focus, Key, Mouse, Mousemotion, Item
- Choice : Focus, Key, Mouse, Mousemotion, Item
- List : Focus, Key, Mouse, Mousemotion, Item
- TextField : Focus, Key, Mouse, Mousemotion, Action
- TextArea : Focus, Key, Mouse, Mousemotion
- Dialog : Focus, Key, Mouse, Mousemotion, Window
- FileDialog : Focus, Key, Mouse, Mousemotion, Window
- Menu : Action
- MenuItem : Action
- CheckboxMenuItem : Action, Item
- ScrollPane : Focus, Key, Mouse, Mousemotion
- PopupMenu : Action
- Event 핸들러
- ActionListener → ActionEvent
- FocusListener & FocusAdapter → FocusEvent
- ItemListener → ItemEvent
- KeyListener & KeyAdapter → KeyEvent
- MouseListener & MouseAdapter → MouseEvent
- MouseMotionListener & MouseMotionAdapter → MouseEvent
- WindowListener & WindowAdapter → WindowEvent
- Event 수행시점
- Action : 마우스 클릭이나 키보드의 엔터 키를 누르거나 메뉴에서 아이템을 선택했을 때
- Focus : 커서의 위치가 바뀌면서 특정 객체가 커서를 얻거나 잃을 때
- Key : 키보드를 눌렀을 때
- Mouse : 마우스의 버튼을 누르고 있거나 뗐을 때, 혹은 클릭(눌렀다 뗌)했을 때, 마우스가 특정 객체의 내부에 들어갔을 때나 특정 객체네서 빠져나왔을 때
- MouseMotion : 마우스가 움직이거나 마우스를 드래그 했을 때
- Item : List나 Choice 등과 같이 아이템을 가지는 객체의 선택된 아이템에 변화가 있을 때
- Window : 다이얼로그나 프레임 등과 같이 열기, 닫기, 활성, 비활성, 최소화 등 해당 움직임에 대한 응답이 필요할 때
Event 작성법
- Event 작성 순서
- Event를 발생시키고자 하는 대상 객체와 Event 클래스의 종류를 선정한다.
- 대상 객체에게 해당 Event의 Handler를 추가한다.
- 해당 Event 발생시 처리될 내용을 정의한 객체를 생성한다. (Event 객체 구현)
Event 객체 유형 정의
Listener를 구현하거나 Adapter를 상속받은 임의의 클래스를 생성하는 방법
import java.awt.*;
import java.awt.event.*;
public class Round19_Ex01 {
public static void main(String[] args) {
new Round19_Ex01_Sub();
}
class ActionDefine implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
class Round19_Ex01_Sub extends Frame {
....
private Button bt = new Button("닫기");
public Round19_Ex01_Sub() {
super("Event!");
....
}
public void init() {
GridBagLayout gridbag = new GrdiBagLayout();
GridBagConstraints gc = new GridBagConstraints();
this.setLayout(gridbag);
girdbag.setConstraints(bt, gc);
this.add(bt);
}
public void start() {
bt.addActionEventListener(new ActionDefine());
}
}
}
현재 클래스에 Listener를 구현하는 방법
import java.awt.*;
import java.awt.event.*;
public class Round19_Ex01 {
public static void main(String[] args) {
new Round19_Ex01_Sub();
}
class Round19_Ex01_Sub extends Frame implements ActionListener {
....
private Button bt = new Button("닫기");
public Round19_Ex01_Sub() {
super("Event!");
....
}
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
public void init() {
GridBagLayout gridbag = new GrdiBagLayout();
GridBagConstraints gc = new GridBagConstraints();
this.setLayout(gridbag);
girdbag.setConstraints(bt, gc);
this.add(bt);
}
public void start() {
bt.addActionEventListener(this);
}
}
}
익명 중첩 클래스를 사용하는 방법
import java.awt.*;
import java.awt.event.*;
public class Round19_Ex01 {
public static void main(String[] args) {
new Round19_Ex01_Sub();
}
class Round19_Ex01_Sub extends Frame {
....
private Button bt = new Button("닫기");
public Round19_Ex01_Sub() {
super("Event!");
....
}
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
public void init() {
GridBagLayout gridbag = new GrdiBagLayout();
GridBagConstraints gc = new GridBagConstraints();
this.setLayout(gridbag);
girdbag.setConstraints(bt, gc);
this.add(bt);
}
public void start() {
bt.addActionEventListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
}
}
}
Event 클래스들
ActionListener 와 ActionEvent
java.lang.Object -> java.util.event.Object -> java.awt.AWTEvent -> java.awt.event.ActionEvent
import java.awt.*;
import java.awt.event.*;
public class Round19_Ex02 {
public static void main(String[] args) {
new Round19_Ex02_Sub();
}
class Round19_Ex02_Sub extends Frame implements ActionListener {
....
private Label lb = new Label("결과표시 : 현재 누른 버튼이 없습니다."
, Label.CENTER);
private Button bt = new Button("버튼1");
private Button bt2 = new Button("버튼2");
public Round19_Ex02_Sub() {
super();
....
}
public void init() {
BorderLayout border = new BorderLayout();
this.setLayout(border);
Panel p = new Panel();
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints gc = new GridBagConstraints();
p.setLayout(gridbag);
gc.inset = new Insets(0, 0, 0, 10);
gridbag.setConstraints(bt, gc);
p.add(bt);
gc.insets = new Insets(0, 10, 0, 0);
gridbag.setConstraints(bt1, gc);
p.add(bt1);
this.add("North",lb);
this.add("South", p);
}
public void start() {
bt.addActionEventListener(this);
bt1.addActionEventListener(this);
}
public void actionPerformed(ActionEvent e) {
if( e.getSource() == bt ){
lb.setText("결과표시 : 버튼1을 누르셨습니다.");
} else if ( e.getSource() == bt1 ) {
lb.setText("결과표시 : 버튼2를 누르셨습니다.");
}
}
}
}
FocusListener, FocusAdapter 와 FocusEvent
import java.awt.*;
import java.awt.event.*;
public class Round19_Ex03 {
public static void main(String[] args) {
new Round19_Ex03_Sub();
}
class Round19_Ex03_Sub extends Frame implements FocusListener {
private BorderLayout b1 = new BorderLayout();
private List<Label> lbs = Arrays.asList(
new Label("이름 = ", Label.RIGHT)
, new Label("주민번호 = ", Label.RIGHT)
);
private List<TextField> tfs = Arrays.asList(
new TextField()
, new TextField()
, new TextField()
);
private Button bt = new Button("확인");
private Button bt1 = new Button("취소");
public Round19_Ex03_Sub() {
super("Focus Event!!");
this.init();
this.start();
this.setSize(200, 100);
this.setVisible(true);
}
public void init() {
this.setLayout(b1);
Panel p = new Panel(new GridLayout(2, 1));
p.add(tfs.get(0));
Panel p1 = new Panel(new GridLayout(1, 2, 5, 5));
p1.add(tfs.get(1));
p1.add(tfs.get(2));
p.add(p1);
this.add("Center", p);
Panel p2 = new Panel(new GridLayout(2, 1));
p2.add(lbs.get(0));
p2.add(lbs.get(1));
this.add("West", p2);
Panel p3 = new Panel(new FlowLayout(FlowLayout.RIGHT));
p3.add(bt);
p3.add(bt1);
this.add("South", p3);
}
public void start() {
tfs.get(0).addFocusListener(this);
tfs.get(0).addFocusListener(this);
}
pulic void focusGained(FocusEvent e) {
if( e.getSource() == tfs.get(0)) {
int x = tfs.get(0).getText().trim().length();
if( x == 0 ) {
tf.requestFocus();
}
} else if ( e.getSource() == tfs.get(1)) {
int x = tfs.get(1).getText().trim().length();
if( x != 6 ) {
tfs.get(1).setText("");
tfs.get(1).requestFocus();
}
}
}
public void focusLost(FocusEvent e) {
}
}
}
ItemListener 와 ItemEvent
import java.awt.*;
import java.awt.event.*;
public class Round19_Ex04_Sub extends Frame implements ItemListener {
private FlowLayout f1 = new FlowLayout();
private Choice ch = new Choice();
private List li = new List(3, false);
public Round19_Ex04_Sub() {
super("Test");
this.init();
this.start();
this.setSize(300, 200);
this.setVisible(true);
}
public void init() {
this.setLayout(f1);
List<String> ss = Arrays.asList("AAA","BBB","CCC");
for(String s : ss) {
ch.add(ss);
}
this.add(ch);
for(String s : ss) {
li.add(ss);
}
this.add(li);
}
public void start() {
ch.addItemListener(this);
li.addItemListener(this);
}
public void paint() {
}
public void itemStateChanged(ItemEvent e) {
if(e.getSource() == ch) {
System.out.println("얻어온 문자열 = " + ch.getSelectedItem());
} else (e.getSource() == li) {
System.out.println("얻어온 문자열 = " + li.getSelectedItem());
}
}
}
public class Round19_Ex04 {
public static void main(String[] args) {
new Round19_Ex04_Sub();
}
}
KeyListener, KeyAdapter 와 KeyEvent
import java.awt.*;
import java.awt.event.*;
public class Round19_Ex05_Sub extends Frame implements KeyListener {
private FlowLayout f1 = new FlowLayout();
private TextField tf = new TextField(10);
private Label lb = new Label("-", Label.Center);
private TextField tf1 = new TextField(10);
public Round19_Ex05_Sub() {
super("Test");
this.init();
this.start();
this.setSize(300, 200);
this.setVisible(true);
}
public void init() {
this.setLayout(f1);
this.add(tf);
this.add(lb);
this.add(tf1);
}
public void start() {
ch.addItemListener(this);
li.addItemListener(this);
}
public void paint(Graphincs g) {
}
public void keyPressed(KeyEvent e) {}
public void keyReleased(KeyEvent e) {
String str = tf.getText().trim();
if(str.length() == 6) {
tf1.requestFocus();
}
}
publc void keyTyped(KeyEvent e) {}
}
public class Round19_Ex05 {
public static void main(String[] args) {
new Round19_Ex05_Sub();
}
}
MouseListener, MouseAdapter 와 MouseEvent
import java.awt.*;
import java.awt.event.*;
public class Round19_Ex06_Sub extends Frame implements MouseListener {
private Button bt = new Button("나를 눌러봐요");
public Round19_Ex06_Sub() {
super("Test");
this.init();
this.start();
this.setSize(300, 200);
this.setVisible(true);
}
public void init() {
this.setLayout(null);
bt.setBounds(50, 50, 80, 30);
this.add(bt);
}
public void start() {
bt.addMouseListener(this);
}
public void paint(Graphincs g) {
}
public void mouseClicked(MouseEvent e) {
System.out.pointln("클릭했다.");
}
public void mousePressed(MouseEvent e) {
System.out.pointln("누른상태");
}
public void mouseReleased(MouseEvent e) {
System.out.pointln("뗀 상태");
}
public void mouseEntered(MouseEvent e) {
System.out.pointln("해당 위치에 들어 왔다.");
bt.setLocation((int)(Math.random() * 300) - 80, (int)(Math.random() * 200) - 30);
}
public void mouseExited(MouseEvent e) {
System.out.pointln("벗어 났다.");
}
}
public class Round19_Ex06 {
public static void main(String[] args) {
new Round19_Ex06_Sub();
}
}
MouseMotionListener, MouseMotionAdapter 와 MouseMotionEvent
import java.awt.*;
import java.awt.event.*;
public class Round19_Ex07_Sub extends Frame
implements MouseMotionListener, KeyListener, FocusListener, ActionListener {
private Label lb = new Label("x = 000, y = 000", Label.RIGHT);
private Label lb1 = new Label("x = 000, y = 000");
private Label jumin_lb = new Label("Jumin = ", Label.RIGHT);
private TextField jumin_tf1 = new TextField(6);
private Label jumin_dasi = new Label("-", Label.CENTER);
private TextField jumin_tf2 = new TextField(7);
private Buffton jumin_bt = new Button("중첩");
private Panel p = null;
public Round19_Ex07_Sub() {
super("Test");
this.init();
this.start();
this.setSize(500, 500);
this.setVisible(true);
}
public void init() {
this.setLayout(new BorderLayout());
this.add("North", lb);
p = new Panel(new GridBagLayout());
p.add(jumin_lb);
p.add(jumin_tf1);
p.add(jumin_dasi);
p.add(jumin_tf2);
p.add(jumin_bt);
this.add("Center",p);
this.add("South",lb1);
}
public void start() {
this.addMouseMotionListener(this);
p.addMouseMotionListener(this);
lb.addMouseMotionListener(this);
lb1.addMouseMotionListener(this);
jumin_tf1.addKeyListener(this);
jumin_tf1.addFocusListener(this);
jumin_bt.addActionListener(this);
}
public void mouseMoved(MouseEvent e) {
int xpos = e.getX();
int ypos = e.getY();
lb1.setText("x = " + xpos + ", y = " + ypos);
}
public void mouseDragged(MouseEvent e) {
int xpos = e.getX();
int ypos = e.getY();
lb.setText("x = " + xpos + ", y = " + ypos);
}
public void keyPressed(KeyEvent e) {
if( e.getSource() == jumin_tf1 ) {
String str = jumin_tf1.getText().trim();
if(str.length() == 5) {
jumin_tf2.requestFocus();
}
}
}
public void keyReleased(KeyEvent e) {
if( e.getSource() == jumin_tf1 ) {
String str = jumin_tf1.getText().trim();
if(str.length() == 6) {
jumin_tf2.requestFocus();
}
}
}
public void keyTyped(KeyEvent e) {}
public void focusGained(FocusEvent e) {
if( e.getSource() == jumin_tf1 ) {
String str = jumin_tf1.getText().trim();
if(str.length() != 6) {
jumin_tf1.setText("");
jumin_tf1.requestFocus();
}
}
}
public void focusLost(FocusEvent e) {}
public void actionPerformed(ActionEvent e) {
if( e.getSource() == jumin_bt ) {
String first = jumin_tf1.getText().trim();
String second = jumin_tf2.getText().trim();
if( first.length() != 6 || second.length() != 7 ) {
jumin_tf1.setText("");
jumin_tf2.setText("");
jumin_tf1.requestFocus();
return;
}
final Dialog dlg = new Dialog(this, "OK", true);
dlg.setLayout(new BorderLayout());
String sss = "주민번호 : " +
first + "-" + second + "는 사용할 수 있다.";
dlg.add("Center", new Label(sss, Label.CENTER));
Button bt = new Button("확인");
Panel pp = new Panel(new FlowLayout());
pp.add(bt);
bt.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
dlg.setVisible(false);
}
});
dlg.add("South", pp);
dlg.setSize(300, 100);
dlg.setVisible(true);
}
}
}
public class Round19_Ex07 {
public static void main(String[] args) {
new Round19_Ex07_Sub();
}
}
WindowListener, WindowAdapter 와 WindowEvent
import java.awt.*;
import java.awt.event.*;
public class Round19_Ex08_Sub extends Frame {
public Round19_Ex08_Sub() {
super("Test");
this.init();
this.start();
this.setSize(300, 200);
this.setVisible(true);
}
public void init() {
}
public void start() {
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
public class Round19_Ex08 {
public static void main(String[] args) {
new Round19_Ex08_Sub();
}
}
과제
과제1. 파일 입 출력을 이용하여 로컬 게시판을 만들어보자.
기본 화면은 다음과 같이 글 목록이 좌측에 나타난다. 새로고침 버튼을 누르면 글 목록이 갱신된다. 글 쓰기 버튼은 글을 쓸 수 있는 창이 나타나고 목록에서 글을 더블 클릭하면 우측 화면에 내용이 표시된다. 수정, 삭제 버튼은 글의 내용을 수정하거나 삭제하는 기능이다. 종료 버튼은 게시판 창을 닫는 기능이다. 글쓰기 버튼에서는 파일을 첨부하는 기능도 포함한다. 나머지 화면은 다음과 같다.