어서와 Java는 처음이지! 제10장 이벤트 처리.

Slides:



Advertisements
Similar presentations
Event-Driven Programming You might have realized in creating a GUI and clicking on the JButtons that nothing happens Clicking on a JButton causes the JVM.
Advertisements

Managing Input Events in Swing Week 5 Workshop Lyn Bartram.
Computer Science 209 Graphics and GUIs. Working with Color The class java.awt.Color includes constants for typical color values and also supports the.
Jan Event Handling -1.1 Yangjun Chen Dept. Business Computing University of Winnipeg.
Event Handling Events and Listeners Timers and Animation.
Gui Interfaces a la Swing Up to speed with Swing by Steven Gutz is a good source It don’t mean a thing if it ain’t got that swing Duke Ellington.
1 Lecturte 14Lecture 7 Applications of Graphics Overview  Conversions Between Applications and Applets  Handling Mouse Events  Handling Keyboard Events.
Unit 111 Event-Driven Programming Listener or Event handler Example: Handling Button Events Example: Handling Mouse Events Example: Handling Keyboard Events.
Intermediate Java1 An example that uses inner classes Week Four Continued.
Graphical User Interfaces
Mouse Events. Handling Mouse Events Java provides two listener interfaces to handle mouse events: MouseListener;  MouseListener;  MouseMotionListener.
Introduction to GUI Java offers a great number of pre-defined classes to support the development of graphical user interfaces –These are broken down into.
GUI Components and Design Here we add one more component to our programs, JButtons –JButtons can only be inserted into JPanels (or JApplets) –Clicking.
Cs884(Prasad)java12AWT1 Abstract Windowing Toolkit Support for Graphical User Interface (Event-driven programming)
CS 11 java track: lecture 4 This week: arrays interfaces listener classes inner classes GUI callbacks.
SD2071 Games Programming Abstraction, inheritance and interfaces Exceptions Two dimensional arrays Java collections framework Files Aaron Kans.
Previous programs used a JLabel for OUTPUT. Another Swing component that can be used for both user input and output is the JTextfield. Suppose we want.
1 Outline 1 Introduction 2 Overview of Swing Components 3 JLabel 4 Event Handling 5 TextFields 6 How Event Handling Works 7 JButton 8 JCheckBox and JRadioButton.
OOP (Java): GUI II/ OOP Objectives – –describe some more GUI features: JPanel, and mouse listeners/adapters Semester 2,
GUI 프로그래밍과 AWT(2) 컴퓨터 공학실험 (I) 인공지능 연구실. 2 AWT Event Model  Java 의 Event Model 1.Event : 사용자가 Program 에 가한 행동 2.Event Source : Event 가 일어난 근원 3.Event.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
Java's Graphical User Interface Toolkit
COMP 321 Week 2. Outline Event-Driven Programming Events, Event Sources, Event Listeners Button and Timer Events Mouse Events, Adapters.
 Definition: An event is an object thrown in response to a user of programmatic action  Definition: A listener is a series of methods that executes in.
Omer Boyaci.  GUIs are event driven.  When the user interacts with a GUI component, the interaction—known as an event—drives the program to perform.
1 GUIs, Layout, Drawing Rick Mercer. 2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces (GUIs)
Event Handling. Event Driven Programming Flow of programs is determined by events. The Operating system recognizes events and passes them to the particular.
For (int i = 1; i
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 21.1 Test-Driving the Painter Application.
Event Handling. 2 GUIs are event driven –Generate events when user interacts with GUI e.g., moving mouse, pressing button, typing in text field, etc.
CMSC 341 Making Java GUIs Functional. 09/29/2007 CMSC 341 Events 2 More on Swing Great Swing demo at /demos/jfc/SwingSet2/SwingSet2Plugin.html.
Event Handling. The signals that a program receives from the operating system as a result of the actions are called events. A window based program is.
Agenda Introduction. Event Model. Creating GUI Application. Event Examples.
Chapter 14 – Using Layout Managers and Events Dr. James Burns –
1 GUIs, Layout, Drawing Rick Mercer. 2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces (GUIs)
Index Event Handling Events Event Source Event Listener Event Classes Action Event Class Adjustment event Class Event Source Event Listener Interface Using.
GUI DYNAMICS Lecture 11 CS2110 – Fall GUI Statics and GUI Dynamics  Statics: what’s drawn on the screen  Components buttons, labels, lists, sliders,
Mouse Listeners Moving the mouse will also generate events like the Timer –To have your program respond, you must implement either or both of MouseListener.
(c) by Elizabeth Sugar Boese.1 Chapter 6 Events - Lecture Slides.
Events in JAVA Needed for Applets and GUI based programs. Applet uses GUI to interact with user. Most of the events are generated by Mouse, Keyboard.
Event-Driven Programming CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
13. Advanced GUI Components
Nested Classes and Event Handling Chapter 10. Overview We explain how to write Java code that responds to events. The Timer class can be used to respond.
Chapter 6: Events in Java 1.0 Model –Event class –selecting component to handle –handleEvent method –helper methods (action, keyUp, mouseUp, etc.) 1.1.
What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event.
Institute of Ambient Intelligence 2009, Choi, Namseok, Dongseo Univ., Java 기초 ( 컴포넌트와 이벤트 처리 프로그래밍 ) Choi,
CSI 3125, Preliminaries, page 1 Event Handling. CSI 3125, Preliminaries, page 2 Event Handling An Event Change in the state of an object is known as event.
Mouse Events GUI. Types of Events  Below, are some of the many kinds of events, swing components generate. Act causing EventListener Type User clicks.
GUI Tutorial Day 4. More GUI action  adding a Mouse Listener  SimpleDots  Simple mouse listener  Draw an oval where the mouse is clicked  Box example.
TENTH LECTURE Event and listener. Events and Listeners An event can be defined as a type of signal to the program that something has happened. The event.
어서와 Java는 처음이지! 제10장 이벤트 처리.
Mouse, Keyboard, Sounds, and Images JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin,
Dept. of CSIE, National University of Tainan 10/21/2012 Responding to User Input.
GUI Programming in Java Hao Jiang Boston College April, 2009.
JAVA 실습 6 주차 Jin-Ho, Jang M.S. Hanyang Univ. HPC&OT Lab. 1HPC & OT Lab.
Object-Orientated Analysis, Design and Programming
Lecture 8 Object Oriented Programming Using Java
Programming in Java, 2e Sachin Malhotra Saurabh Choudhary.
Chapter 12 Event-Driven Programming
Event Handling Chapter 2 Objectives
Computer Science 209 Graphics and GUIs.
Programming in Java Event Handling
CSE 114 – Computer Science I Event Programming
GUI Programming III: Events
CSE Software Engineering Fall 1999 Updated by J. Brown
Event-driven programming for GUI
어서와 Java는 처음이지! 제13장 실전프로젝트.
Making Java GUIs Functional
Chapter 14 – Using Layout Managers and Events
Presentation transcript:

어서와 Java는 처음이지! 제10장 이벤트 처리

이벤트-구동 프로그래밍 이벤트-구동 프로그래밍(event-driven programming): 프로그램의 실행이 이벤트의 발생(마우스 버튼 클릭, 더블 클릭, 마우스 이동 등)에 의하여 결정되는 방식

이벤트-구동 프로그래밍(Event Driven) 마우스 버튼 클릭, 더블 클릭, 마우스 이동 등에 응답하는 형태로 작성하는 프로그래밍 윈도우 환경에서는 대부분의 응용프로그램이 이벤트-기반 프로그래밍 방식으로 작성된다. 일반 프로그램 이벤트-기반 프로그램

GUI 프로그램 모델 이벤트 청취자 이벤트 처리 GUI 컴포넌트 코드 Event listener 이벤트 처리 청취자 등록 Event source 이벤트 처리 코드 Event handler 이벤트 효과 4

이벤트 처리 과정

이벤트 리스너 발생된 이벤트 객체에 반응하여서 이벤트를 처리하는 객체를 이벤트 리스너(event listener)라고 한다.

이벤트 처리 과정 이벤트 리스너 클래스를 작성한다. (ActionEvent에 대한 청취자 클래스: ActionListener 인터페이스를 구현한다. actionPerformed(ActionEvent e) 메소드를 재정의 ) class MyListener implements ActionListener { public void actionPerformed(ActionEvent e) { ... // Action 이벤트를 처리하는 코드가 여기에 들어간다. }

이벤트 처리 과정 (2) 이벤트 리스너를 이벤트 소스에 등록한다. public class MyFrame extends JFrame { public MyFrame() // 생성자에서 컴포넌트를 생성하고 추가한다. { button = new JButton("동작“); // 버튼 생성 button.addActionListener(new MyListener()); ... } 이벤트 리스너를 컴포넌트에 붙인다.

이벤트의 실제 예 9 마우스로 메뉴 선택 키보드로 메뉴 선택 (Mouse Event, 키보드 입력 Action Event) (Key Event, Action Event) 키보드 입력 (Key Event) 마우스로 버튼 클릭 (Mouse Event, Action Event) 마우스로 윈도우 크기 조절 (Mouse Event, Container Event)

자바의 이벤트 기반 GUI 응용프로그램 구성 10

이벤트 객체 이벤트 객체란? 이벤트 객체의 종류 이벤트가 발생할 때, 발생한 이벤트에 관한 정보를 가진 객체 11 이벤트 객체란? 이벤트가 발생할 때, 발생한 이벤트에 관한 정보를 가진 객체 이벤트 리스너에 전달됨 이벤트 리스너 코드에서 이벤트가 발생한 상황을 파악할 수 있게 함 이벤트 객체의 종류 java.util.EventObject EventObject java.awt.AWTEvent AWTEvent ListSelectionEvent javax.swing.event.ListSelectionEvent java.awt.event.* ActionEvent AdjustmentEvent ComponentEvent ItemEvent TextEvent ContainerEvent FocusEvent InputEvent PaintEvent WindowEvent MouseEvent KeyEvent

이벤트 객체 EventObject 클래스를 상속받는다. (예) MouseEvent 클래스 이벤트를 발생시킨 이벤트 소스 등의 여러 가지 정보를 제공한다. public void actionPerformed(ActionEvent e) { button = (JButton)e.getSource(); ... }

이벤트 객체에 포함된 정보 이벤트 객체가 포함하는 정보 이벤트에 따라 조금씩 다른 정보 포함 이벤트 소스 알아 내기 13 이벤트 객체가 포함하는 정보 이벤트 종류 이벤트 소스 이벤트가 발생한 화면 좌표 이벤트가 발생한 컴포넌트 내 좌표 버튼이나 메뉴 아이템에 이벤트가 발생한 경우 버튼이나 메뉴 아이템의 문자열 클릭된 마우스 버튼 번호 마우스의 클릭 횟수 키가 눌러졌다면 키의 코드 값과 문자 값 체크박스, 라디오버튼 등과 같은 컴포넌트에 이벤트가 발생하였다면 체크 상태 이벤트에 따라 조금씩 다른 정보 포함 ActionEvent 객체 : 액션 문자열 MouseEvent 객체 : 마우스의 위치 정보, 마우스 버튼, 함께 눌러진 키 정보 등 ItemEvent 객체 : 아이템의 체크 상태 이벤트 소스 알아 내기 Object EventObject.getSource() 발생한 이벤트의 소스 컴포넌트 리턴 Object 타입으로 리턴하므로 캐스팅하여 사용 모든 이벤트 객체에 대해 적용

이벤트 객체의 메소드 EventObject AWTEvent ActionEvent ComponentEvent ItemEvent 14 EventObject Object getSource() AWTEvent ActionEvent ComponentEvent ItemEvent String getActionCommand() Object getItem() int getStateChange() InputEvent int getModifiers() MouseEvent KeyEvent int getButton() int getClickCount() Point getPoint() int getX() int getY() char getKeyChar() int getKeyCode() String getKeyText()

이벤트 객체와 이벤트 소스 15

이벤트 리스너(Event Listener) 16 이벤트 리스너란? 이벤트를 처리하는 코드 클래스로 작성 JDK에서 이벤트 리스너 작성을 위한 인터페이스(interface) 제공 개발자가 리스너 인터페이스의 추상 메소드 구현 이벤트가 발생하면 자바 플랫폼은 리스너 인터페이스의 추상 메소드 호출 예) ActionListener 인터페이스 예) MouseListener 인터페이스 interface ActionListener { // 아래 메소드를 개발자가 구현해야 함 public void actionPerformed(ActionEvent e); // Action 이벤트 발생시 호출됨 } interface MouseListener { // 아래의 5개 메소드를 개발자가 구현해야 함 public void mousePressed(MouseEvent e); // 마우스 버튼이 눌러지는 순간 호출 public void mouseReleased(MouseEvent e); // 눌러진 마우스 버튼이 떼어지는 순간 호출 public void mouseClicked(MouseEvent e); // 마우스가 클릭되는 순간 호출 public void mouseEntered(MouseEvent e); // 마우스가 컴포넌트 위에 올라가는 순간 호출 public void mouseExited(MouseEvent e); // 마우스가 컴포넌트 위에서 내려오는 순간 호출 } 16

이벤트 리스너 등록 이벤트 리스너 등록 이벤트 리스너 등록 메소드 이벤트 리스너가 등록된 컴포넌트에만 이벤트 전달 17 이벤트 리스너 등록 이벤트를 받아 처리하고자 하는 컴포넌트에 이벤트 리스너 등록 이벤트 리스너 등록 메소드 Component.addXXXListener(listener) xxx : 이벤트 명 listener : 이벤트 리스너 객체(리스너를 구현한 객체) 예) addMouseListener(), addActionListener(), addFocusListener() 등 이벤트 리스너가 등록된 컴포넌트에만 이벤트 전달 이벤트 리스너가 등록된 컴포넌트만 이벤트 리스너 코드 작동

리스너 인터페이스와 메소드 18

이벤트 처리기를 어디에… (1) 독립적인 클래스로 이벤트 처리기를 작성 (2) 내부 클래스로 이벤트 처리기를 작성 이벤트 처리 방법 (3) 프레임 클래스에 이벤트 처리를 구현 (4) 무명 클래스를 사용하는 방법 (5) 람다식을 이용하는 방법

(1) 독립적인 클래스 작성 import javax.swing.*; import java.awt.event.*; class MyListener implements ActionListener { public void actionPerformed(ActionEvent e) { JButton button = (JButton) e.getSource(); button.setText("마침내 버튼이 눌려졌습니다."); // label.setText("마침내 버튼이 눌려졌습니다."); }

독립적인 클래스 작성 class MyFrame extends JFrame { private JButton button; private JLabel label; public MyFrame() { this.setSize(300, 200); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setTitle("이벤트 예제"); JPanel panel = new JPanel(); button = new JButton("버튼을 누르시오"); label = new JLabel("아직 버튼이 눌려지지 않았습니다"); button.addActionListener(new MyListener()); panel.add(button); panel.add(label); this.add(panel); this.setVisible(true); } public class ActionEventTest1 { public static void main(String[] args) { MyFrame t = new MyFrame();

독립적인 클래스 방법 문제점: 버튼이 눌려 질 때 사건이 발생한 버튼의 텍스트가 아니라 레이블의 텍스트를 변경하려면? 외부 클래스의 label에 접근할 수 없다.

내부 클래스 방법 (2) 만약 MyListener라는 클래스를 별도의 클래스로 하면 MyFrame 안의 멤버 변수들을 쉽게 사용할 수 없다. 일반적으로 MyListener 클래스를 내부 클래스로 만든다.

(2) 내부 클래스 방법 class MyFrame extends JFrame { private JButton button; private JLabel label; public MyFrame() { this.setSize(300, 200); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setTitle("이벤트 예제"); JPanel panel = new JPanel(); button = new JButton("버튼을 누르시오"); label = new JLabel("아직 버튼이 눌려지지 않았습니다"); button.addActionListener(new MyListener()); panel.add(button); panel.add(label); this.add(panel); this.setVisible(true); }

내부 클래스 방법 private class MyListener implements ActionListener { public void actionPerformed(ActionEvent e) { if (e.getSource() == button) { label.setText("마침내 버튼이 눌려졌습니다."); } public class ActionEventTest { public static void main(String[] args) { MyFrame t = new MyFrame(); 내부 클래스 label 에 접근할 수 있다.

내부 클래스 방법

MyFrame에서 이벤트도 처리하는 방법 (3) 더 많이 사용되는 방법은 MyFrame 클래스가 JFrame을 상속받으면서 동시에 ActionListener 인터페이스도 구현하는 경우이다.

(3) MyFrame이 이벤트도 처리 ... class MyFrame extends JFrame implements ActionListener { public MyFrame() { button = new JButton("버튼을 누르시오"); label = new JLabel("아직 버튼이 눌려지지 않았습니다"); button.addActionListener(this); } public void actionPerformed(ActionEvent e) { if (e.getSource() == button) { label.setText("마침내 버튼이 눌려졌습니다."); 이벤트도 처리

(4) 무명 클래스를 사용하는 방법 안드로이드에서 많이 사용된다! class MyFrame extends JFrame { ... public MyFrame() { button = new JButton("버튼을 누르시오"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (e.getSource() == button) { label.setText("마침내 버튼이 눌려졌습니다."); } }); 안드로이드에서 많이 사용된다!

(5) 람다식을 이용하는 방법 import javax.swing.*; class MyFrame extends JFrame { private JButton button; private JLabel label; public MyFrame() { this.setSize(300, 200); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setTitle("이벤트 예제"); JPanel panel = new JPanel(); button = new JButton("버튼을 누르시오"); label = new JLabel("아직 버튼이 눌려지지 않았습니다"); button.addActionListener(e -> { label.setText("마침내 버튼이 눌려졌습니다."); }); panel.add(button); panel.add(label); this.add(panel); this.setVisible(true); }

LAB: 키패드 만들기 숫자를 입력할 수 있는 키패드 프로그램을 작성하여 보자.

SOLUTION public class KeyPad extends JFrame implements ActionListener { private JTextField txt; private JPanel panel; public KeyPad() { txt = new JTextField(20); add(txt, BorderLayout.NORTH); panel = new JPanel(); panel.setLayout(new GridLayout(3, 3)); add(panel, BorderLayout.CENTER); for (int i = 1; i <= 9; i++) { JButton btn = new JButton("" + i); btn.addActionListener(this); btn.setPreferredSize(new Dimension(100, 100)); panel.add(btn); } pack(); setDefaultCloseOperation(EXIT_ON_CLOSE); setVisible(true);

SOLUTION @Override public void actionPerformed(ActionEvent e) { String actionCommand = e.getActionCommand(); txt.setText(txt.getText() + actionCommand); } public static void main(String[] args) { new KeyPad();

LAB: 퍼즐 게임 타일을 클릭하면 비어있는 옆의 공간으로 이동하는 퍼즐 게임을 작성해보자.

SOLUTION class MyButton extends JButton { static int count=0; int index; public MyButton(String s) super(s); index = count++; } public class Puzzle extends JFrame implements ActionListener { MyButton[] buttons; MyButton reset; public Puzzle() { super("puzzle"); JPanel panel = new JPanel(); panel.setLayout(new GridLayout(0, 3, 2, 2)); buttons= new MyButton[9]; for(int i=0; i<8; i++) buttons[i] = new MyButton(""+(i+1)); buttons[8] = new MyButton(" "); for(int i=0; i<9; i++) panel.add(buttons[i]); buttons[i].addActionListener(this); add(panel, BorderLayout.CENTER);

SOLUTION reset = new MyButton("reset"); reset.setBackground(Color.red); reset.setForeground(Color.yellow); add(reset, BorderLayout.SOUTH); // reset.addActionListener(this); setSize(300, 300); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void actionPerformed(ActionEvent e) { MyButton b = (MyButton) e.getSource(); if( b.getText().equals(" ")==true) return; if( b.index == 0 ){ if( buttons[1].getText().equals(" ") ) { buttons[1].setText(b.getText()); b.setText(" "); } if( buttons[3].getText().equals(" ") ) { buttons[3].setText(b.getText()); b.setText(" "); } ...

SOLUTION Try!!!!!!!(완성해보자), reset??? if( b.index == 8 ){ if( buttons[5].getText().equals(" ") ) { buttons[5].setText(b.getText()); b.setText(" "); } if( buttons[7].getText().equals(" ") ) { buttons[7].setText(b.getText()); b.setText(" "); } } public static void main(String[] args) { new Puzzle(); Try!!!!!!!(완성해보자), reset???

LAB: 가위 바위 보 게임 가위, 바위, 보 게임을 작성하여 보자.

SOLUTION public class RockPaperScissor extends JFrame implements ActionListener { static final int ROCK = 0; static final int PAPER = 1; static final int SCISSOR = 2; private JPanel panel; private JTextField output; private JTextField information; private JButton rock; private JButton paper; private JButton scissor; public RockPaperScissor() { setTitle("가위, 바위, 보"); setSize(400, 300); setDefaultCloseOperation(EXIT_ON_CLOSE); panel = new JPanel(); panel.setLayout(new GridLayout(0, 3)); information = new JTextField("아래의 버튼 중에서 하나를 클릭하시오!"); output = new JTextField(20);

SOLUTION rock = new JButton("ROCK"); paper = new JButton("PAPER"); scissor = new JButton("SCISSOR"); rock.addActionListener(this); paper.addActionListener(this); scissor.addActionListener(this); panel.add(rock); panel.add(paper); panel.add(scissor); add(information, BorderLayout.NORTH); add(panel, BorderLayout.CENTER); add(output, BorderLayout.SOUTH); setVisible(true); } public static void main(String[] args) { RockPaperScissor gui = new RockPaperScissor();

SOLUTION @Override public void actionPerformed(ActionEvent e) { Random random = new Random(); int computer = random.nextInt(3); if (e.getSource() == rock) { if (computer == SCISSOR) output.setText("사용자 승리"); else if (computer == ROCK) output.setText("비겼음"); else output.setText("컴퓨터 승리"); } else if (e.getSource() == paper) { if (computer == ROCK) else if (computer == PAPER)

SOLUTION } else if (e.getSource() == scissor) { if (computer == PAPER) output.setText("사용자 승리"); else if (computer == SCISSOR) output.setText("비겼음"); else output.setText("컴퓨터 승리"); }

이벤트의 분류 스윙 컴포넌트에 의하여 지원되는 이벤트는 크게 두 가지의 카테고리로 나누어진다.

저수준 이벤트

의미적 이벤트

액션 이벤트 사용자가 버튼을 클릭하는 경우 사용자가 메뉴 항목을 선택하는 경우 사용자가 텍스트 필드에서 엔터키를 누르는 경우

액션 이벤트 예제 두 개의 버튼을 만들어서 패널의 배경 색을 변경하는 프로그램을 작성하여 보자. 이벤트 리스너는 하나만 생성한다. (어느 버턴인지 구분하여 처리한다)

액션 이벤트 예제 … class MyFrame extends JFrame { private JButton button1; private JPanel panel; public MyFrame() { this.setSize(300, 200); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setTitle("이벤트 예제"); panel = new JPanel(); button1 = new JButton("노란색"); button1.addActionListener(new MyListener()); panel.add(button1); button2 = new JButton("핑크색"); button2.addActionListener(new MyListener()); panel.add(button2); this.add(panel); this.setVisible(true); }

액션 이벤트 예제 private class MyListener implements ActionListener { public void actionPerformed(ActionEvent e) { if (e.getSource() == button1) { panel.setBackground(Color.YELLOW); } else if (e.getSource() == button2) { panel.setBackground(Color.PINK); } public class ChangeBackground { public static void main(String[] args) { MyFrame t = new MyFrame();

실행 결과 화면

이벤트 발생원의 식별 getSource()메소드를 이용하여 이벤트를 발생시킨 객체를 식별한다. getId() 메소드를 이용하여 이벤트의 타입을 식별한다. getActionCommand()메소드를 이용하여 이벤트를 발생시킨 컴포넌트 이름을 식별한다.(버튼의 텍스트) public void actionPerformed(ActionEvent e) { if (e.getSource () == button1){ … }

Key 이벤트 KeyListener 인터페이스 구현 메소드 설 명 keyTyped(KeyEvent e) 사용자가 글자를 입력했을 경우에 호출 keyPressed(KeyEvent e) 사용자가 키를 눌렀을 경우에 호출 keyReleased(KeyEvent e) 사용자가 키에서 손을 떼었을 경우에 호출

KeyListener의 메소드와 키 KeyListener의 3 개 메소드 컴포넌트에 키 이벤트 리스너 등록    53 KeyListener의 3 개 메소드 컴포넌트에 키 이벤트 리스너 등록 컴포넌트의 키 리스너(KeyListener)  컴포넌트 void keyPressed(KeyEvent e) { // 이벤트 처리 루틴 } void keyReleased(KeyEvent e) { void keyTyped(KeyEvent e) {  키를 누르는 순간 누른 키를 떼는 순간  누른 키를 떼는 순간, Unicode 키가 입력된 경우에만 KeyListener의 메소드가 실행되는 순서    component.addKeyListener(myKeyListener);

키이벤트 예제 키보드에서 문자가 입력되면 문자 코드와 키코드, ALT나 SHIFT 키의 상태를 텍스트 영역에 출력한다.

키 이벤트 예제 public class KeyEventTest extends JFrame implements KeyListener { private JPanel panel; private JTextField field; private JTextArea area; public KeyEventTest() { panel = new JPanel(new GridLayout(0, 2)); panel.add(new JLabel("문자를 입력하시오: ")); field = new JTextField(10); panel.add(field); area = new JTextArea(3, 30); add(panel, BorderLayout.NORTH); add(area, BorderLayout.CENTER); field.addKeyListener(this); setTitle("KeyEvent Test"); setSize(400, 200); setVisible(true); } public static void main(String[] args) { new KeyEventTest();

키 이벤트 예제 public void keyTyped(KeyEvent e) { // (3) display(e, "Key Typed "); } public void keyPressed(KeyEvent e) { display(e, "Key Pressed "); public void keyReleased(KeyEvent e) { display(e, "Key Released "); protected void display(KeyEvent e, String s) { char c = e.getKeyChar(); int keyCode = e.getKeyCode(); String modifiers = "Alt: " + e.isAltDown() + "Ctrl: " + e.isControlDown() + "Shift: " + e.isShiftDown(); area.append("" + s + "문자 " + c + "(코드: " + keyCode + ") " + modifiers + "\n");

액션 이벤트 예제 public void keyTyped(KeyEvent e) { // (3) display(e, "KeyTyped "); } public void keyPressed(KeyEvent e) { display(e, "KeyPressed "); public void keyReleased(KeyEvent e) { display(e, "Key Pressed "); protected void display(KeyEvent e, String s) { char c = e.getKeyChar(); int keyCode = e.getKeyCode(); String modifiers = e.isAltDown() + " " + e.isControlDown() + " " + e.isShiftDown(); System.out.println(s + " " + c + " " + keyCode + " " + modifiers);

실행 결과

자동차 게임 예제 키보드의 화살표 키로 움직이는 자동차 애플리케이션을 작성하여 보자.

가상 키(Virtual Key) 60 가상 키는 KeyEvent 클래스에 상수로 선언 가상 키의 일부분 사례

자동차 게임 예제 ... class MyPanel extends JPanel { BufferedImage img = null; int img_x = 100, img_y = 100; public MyPanel() { try { img = ImageIO.read(new File("car.gif")); } catch (IOException e) { System.out.println("no image"); System.exit(1); } addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { int keycode = e.getKeyCode(); switch (keycode) { case KeyEvent.VK_UP: img_y -= 10; break; case KeyEvent.VK_DOWN: img_y += 10; break; case KeyEvent.VK_LEFT: img_x -= 10; break; case KeyEvent.VK_RIGHT: img_x += 10; break; repaint();

자동차 게임 예제 public void keyReleased(KeyEvent arg0) { } public void keyTyped(KeyEvent arg0) { } }); this.requestFocus(); setFocusable(true); } public void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(img, img_x, img_y, null); public class CarGameTest extends JFrame { public CarGameTest() { setSize(300, 300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); add(new MyPanel()); setVisible(true); public static void main(String[] args) { CarGameTest s = new CarGameTest();

실행 결과

LAB: 신호등 신호등을 구현하여 보자. 버튼을 누르면 신호가 변경되도록 한다.

SOLUTION class MyPanel extends JPanel implements ActionListener { boolean flag = false private int light_number = 0; public MyPanel() { setLayout(new BorderLayout()); JButton b = new JButton("traffic light turn on"); b.addActionListener(this); add(b, BorderLayout.SOUTH); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.BLACK); g.drawOval(100, 100, 100, 100); g.drawOval(100, 200, 100, 100); g.drawOval(100, 300, 100, 100); if (light_number == 0) { g.setColor(Color.RED); g.fillOval(100, 100, 100, 100); } else if (light_number == 1) { g.setColor(Color.GREEN); g.fillOval(100, 200, 100, 100);

SOLUTION } else { g.setColor(Color.YELLOW); g.fillOval(100, 300, 100, 100); } @Override public void actionPerformed(ActionEvent arg0) { if (++light_number >= 3) light_number = 0; repaint(); public class MyFrame extends JFrame { public MyFrame() { add(new MyPanel()); setSize(300, 500); setVisible(true); public static void main(String[] arg) { new MyFrame();

Mouse 이벤트

MOUSELISTENER 인터페이스

MouseEvent와 MouseListener,MouseMotionListener 69 Mouse 이벤트 : 사용자의 마우스 조작에 따라 발생하는 이벤트 mouseClicked() : 마우스가 눌러진 위치에서 그대로 떼어질 때 호출 mouseReleased() : 마우스가 눌러진 위치에서 그대로 떼어지든 아니든 항상 호출 mouseDragged(): 마우스가 드래그되는 동안 계속 여러번 호출 마우스가 눌러진 위치에서 떼어지는 경우 메소드 호출 순서 마우스가 드래그될 때 호출되는 메소드 호출 순서 mousePressed(), mouseReleased(), mouseClicked() mousePressed(), mouseDragged(), mouseDragged(),..., mouseDragged(), mouseReleased()

마우스 이벤트 순서 Mouse pressed (# of clicks: 1) X=118 Y=81 Mouse released (# of clicks: 1) X=118 Y=81 Mouse clicked (# of clicks: 1) X=118 Y=81

MouseEvent로부터 얻을 수 있는 정보 71 마우스 포인터의 위치 int getX(), int getY(), Point getPoint() 입력된 마우스 버튼 short getButton() 마우스 클릭 횟수 int getClickCount() public void mousePressed(MouseEvent e) { int x = e.getX(); int y = e.getY(); } public void mousePressed(MouseEvent e) { if(e.getButton() == MouseEvent.BUTTON1) System.out.println("Left Button Pressed"); } public void mouseClicked(MouseEvent e) { if(e.getClickCount() == 2) { // 더블클릭을 처리하는 루틴 }

MOUSEMOTIONLISTENER 인터페이스

Mouse 이벤트 예제 import javax.swing.*; import java.awt.*; import java.awt.event.*; class MyFrame extends JFrame implements MouseListener, MouseMotionListener { public MyFrame() { setTitle("Mouse Event"); setSize(300, 200); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel(); panel.addMouseListener(this); panel.addMouseMotionListener(this); add(panel); setVisible(true); } 마우스 이벤트 처리기를 붙인다.

마우스 이벤트 예제 public void mousePressed(MouseEvent e) { display("Mouse pressed (# of clicks: " + e.getClickCount() + ")", e); } public void mouseReleased(MouseEvent e) { display("Mouse released (# of clicks: " + e.getClickCount() + ")", e); public void mouseEntered(MouseEvent e) { display("Mouse entered", e); public void mouseExited(MouseEvent e) { display("Mouse exited", e); public void mouseClicked(MouseEvent e) { display("Mouse clicked (# of clicks: " + e.getClickCount() + ")", e);

마우스 이벤트 예제 protected void display(String s, MouseEvent e) { System.out.println(s + " X=" + e.getX() + " Y=" + e.getY()); } public void mouseDragged(MouseEvent e) { display("Mouse dragged", e); public void mouseMoved(MouseEvent e) { display("Mouse moved", e); public class MyFrameTest5 { public static void main(String[] args) { MyFrame f=new MyFrame();

자동차 게임 예제(수정) class MyPanel extends JPanel { BufferedImage img = null; int img_x = 0, img_y = 0; public MyPanel() { try { img = ImageIO.read(new File("car.gif")); } catch (IOException e) { System.out.println("no image"); System.exit(1); } addMouseListener(new MouseListener() { public void mousePressed(MouseEvent e) { img_x = e.getX(); img_y = e.getY(); repaint(); public void mouseReleased(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mouseClicked(MouseEvent e) {} });

자동차 게임 예제(수정) public void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(img, img_x, img_y, null); } public class MyFrame extends JFrame { public MyFrame() { add(new MyPanel()); setSize(300, 500); setVisible(true); public static void main(String[] arg) { new MyFrame();

LAB: 사각형 그리기 마우스를 클릭할 때마다 사각형이 화면에 그려지는 예제를 작성하여 보자.

SOLUTION class Rectangle { int x, y, w, h; } class MyPanel extends JPanel implements MouseListener { BufferedImage img = null; int img_x = 0, img_y = 0; Rectangle[] array = new Rectangle[100]; int index = 0; public MyPanel() { this.addMouseListener(this); public void paintComponent(Graphics g) { super.paintComponent(g); for (Rectangle r : array) if (r != null) g.drawRect(r.x, r.y, r.w, r.h);

SOLUTION @Override public void mousePressed(MouseEvent e) { if (index > 100) return; array[index] = new Rectangle(); array[index].x = e.getX(); array[index].y = e.getY(); array[index].w = 50; array[index].h = 50; index++; repaint(); } public void mouseReleased(MouseEvent e) {

SOLUTION @Override public void mouseClicked(MouseEvent e) { } public void mouseEntered(MouseEvent e) { public void mouseExited(MouseEvent e) { public class MouseEventTest extends JFrame { public MouseEventTest() { setSize(300, 300); setTitle("마우스로 사각형 그리기"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); add(new MyPanel()); setVisible(true); public static void main(String[] args) { MouseEventTest s = new MouseEventTest();

LAB: 그림 그리기 이번에는 마우스로 화면에 그림을 그리는 프로그램을 작성하여 보자.

SOLUTION class Point { int x, y; } class MyPanel extends JPanel implements MouseMotionListener { private int index = 0; Point[] array = new Point[1000]; public MyPanel() { this.addMouseMotionListener(this); @Override public void mouseDragged(MouseEvent e) { int x = e.getX(); int y = e.getY(); if (index > 1000) return; array[index] = new Point(); array[index].x = e.getX(); array[index].y = e.getY(); index++; repaint();

SOLUTION public void paintComponent(Graphics g) { super.paintComponent(g); for (Point p : array) if (p != null) g.drawRect(p.x, p.y, 1, 1); } @Override public void mouseMoved(MouseEvent arg0) { public class Scribble extends JFrame { public Scribble() { setSize(300, 300); setTitle("마우스로 그림 그리기"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); add(new MyPanel()); setVisible(true); public static void main(String[] args) { Scribble s = new Scribble();

어댑터 클래스 인터페이스의 경우, 모든 메소드를 구현하여야 한다. 어댑터 클래스(Adaptor Class)를 사용하면 원하는 메소드 만을 구현하는 것이 가능해진다 인터페이스 어댑터 클래스 ComponentListener ComponentAdapter ContainerListener ContainerAdapter FocusListener FocusAdapter KeyListener KeyAdapter MouseListener MouseAdapter MouseMotionListener MouseMotionAdapter WindowListener WindowAdapter

리스너를 사용하는 경우 public class MyClass implements MouseListener { public MyClass() { // ... someObject.addMouseListener(this); } public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mouseClicked(MouseEvent e) {

어댑터를 사용하는 경우 public class MyClass extends MouseAdapter { public MyClass() { // ... someObject.addMouseListener(this); } public void mouseClicked(MouseEvent e) {

자동차 게임 예제(어댑터 버전) ... class MyPanel extends JPanel { BufferedImage img = null; int img_x = 0, img_y = 0; public MyPanel() { try { img = ImageIO.read(new File("car.gif")); } catch (IOException e) { System.out.println("no image"); System.exit(1); } addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { img_x = e.getX(); img_y = e.getY(); repaint(); });

LAB: 카운터 “카운터 증가” 버튼을 누르면 카운터 값이 하나씩 증가되어서 화면에 표시된다.

SOLUTION class MyCounter extends JFrame implements ActionListener { private JLabel label, label1; private JButton button; private int count = 0; public MyCounter() { JPanel panel = new JPanel(); label = new JLabel("Counter"); panel.add(label); label1 = new JLabel("" + count); label1.setFont(new Font("Serif", // 레이블에 폰트를 설정한다. Font.BOLD | Font.ITALIC, 100)); panel.add(label1); button = new JButton("카운터 증가"); panel.add(button); button.addActionListener(this); add(panel); setSize(300, 200); setTitle("My Counter"); setVisible(true); }

Try(카운터 감소 버튼 추가하기!) @Override public void actionPerformed(ActionEvent event) { count++; label1.setText(count + “ “); } Public class CounterTest { public static void main(String[] args) { new MyCounter(); Try(카운터 감소 버튼 추가하기!)

예제 : 더블클릭 시 컨텐트팬의 배경색 변경 더블클릭할 때마다 컨텐트팬의 배경색을 랜덤하게 변경한다. 92 예제 : 더블클릭 시 컨텐트팬의 배경색 변경 더블클릭할 때마다 컨텐트팬의 배경색을 랜덤하게 변경한다. import javax.swing.*; import java.awt.event.*; import java.awt.*; public class ClickAndDoubleClickEx extends JFrame { JPanel contentPane = new JPanel(); ClickAndDoubleClickEx() { setTitle("Click and DoubleClick 예제"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setContentPane(contentPane); contentPane.addMouseListener(new MyMouseListener()); setSize(300,200); setVisible(true); } class MyMouseListener extends MouseAdapter { public void mouseClicked(MouseEvent e) { if(e.getClickCount() == 2) { int r = (int)(Math.random()*256); int g = (int)(Math.random()*256); int b = (int)(Math.random()*256); JPanel p = (JPanel)e.getSource(); p.setBackground(new Color(r,b,g)); public static void main(String [] args) { new ClickAndDoubleClickEx(); 92

Q & A