(Microsoft PowerPoint - java1-lecture7.ppt [\310\243\310\257 \270\360\265\345])

Similar documents
PowerPoint Presentation

gnu-lee-oop-kor-lec10-1-chap10

<4D F736F F F696E74202D20C1A63138C0E520C0CCBAA5C6AE20C3B3B8AE28B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

Microsoft PowerPoint - java1-lecture10.ppt [호환 모드]

PowerPoint Presentation

<4D F736F F F696E74202D20C1A63139C0E520B9E8C4A120B0FCB8AEC0DA28B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

PowerPoint Presentation

10장.key

오버라이딩 (Overriding)

9장.key

<4D F736F F F696E74202D20C1A63230C0E520BDBAC0AE20C4C4C6F7B3CDC6AE203128B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

슬라이드 1

<4D F736F F F696E74202D20C1A63233C0E520B1D7B7A1C7C820C7C1B7CEB1D7B7A1B9D628B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

public class FlowLayoutPractice extends JFrame { public FlowLayoutPractice() { super("flowlayout Practice"); this. Container contentpane = getcontentp

Microsoft PowerPoint - 06-Chapter09-Event.ppt

<4D F736F F F696E74202D20C1A63236C0E520BED6C7C3B8B428B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

Microsoft PowerPoint - java2-lecture5.ppt [호환 모드]

Microsoft PowerPoint - EEL2 Lecture10 -Swing and Event Handling.pptx

Microsoft PowerPoint - 14주차 강의자료

Microsoft PowerPoint - ÀÚ¹Ù08Àå-1.ppt

제8장 자바 GUI 프로그래밍 II

자바GUI실전프로그래밍2_장대원.PDF

11장.key

No Slide Title

Cluster management software

(Microsoft PowerPoint - LZVNQBAJWGTC.ppt [\310\243\310\257 \270\360\265\345])

강의자료

PowerPoint Presentation

No Slide Title

Microsoft PowerPoint - 04-UDP Programming.ppt

Microsoft PowerPoint - [JAVA프로그래밍]9장GUI

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션

Microsoft PowerPoint - Java-03.pptx

<4D F736F F F696E74202D205B4A415641C7C1B7CEB1D7B7A1B9D65D3130C0E5C0CCBAA5C6AEC3B3B8AE>

PowerPoint Presentation

10 이벤트 처리와 그래픽 프로그래밍.key

Microsoft PowerPoint - java1-lecture11.ppt [호환 모드]

PowerPoint 프레젠테이션

슬라이드 1

PowerPoint 프레젠테이션

Java Programing Environment

슬라이드 1

iii. Design Tab 을 Click 하여 WindowBuilder 가자동으로생성한 GUI 프로그래밍환경을확인한다.

모든스윙컴포넌트에는텍스트옆에이미지를추가로표시할수있다. ImageIcon image = new ImageIcon("image.gif"); JLabel label = new JLabel(" 이미지레이블 "); label.seticon(image);

PowerPoint 프레젠테이션

8장.그래픽 프로그래밍

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션

JAVA 프로그래밍실습 실습 1) 실습목표 - 메소드개념이해하기 - 매개변수이해하기 - 새메소드만들기 - Math 클래스의기존메소드이용하기 ( ) 문제 - 직사각형모양의땅이있다. 이땅의둘레, 면적과대각

Cluster management software

자바로

Microsoft PowerPoint - 10장

Microsoft PowerPoint - java1-lecture11.ppt [호환 모드]

Microsoft PowerPoint - ÀÚ¹Ù08Àå-2.ppt

Microsoft PowerPoint - java1-lab5-ImageProcessorTestOOP.pptx

JAVA PROGRAMMING 실습 08.다형성

05-class.key

PowerPoint Presentation

운동시뮬레이션 강의 소개

Microsoft PowerPoint 자바-AWT컴포넌트(Ch8).pptx

중간고사

Microsoft Word - java18-1-final-answer.doc

PowerPoint Presentation

gnu-lee-oop-kor-lec06-3-chap7

PowerPoint 프레젠테이션

PowerPoint Presentation

PowerPoint Presentation

JMF3_심빈구.PDF

JTable과 MVC(Model-View-Controller) 구조 - 모델-뷰-컨트롤러구조는데이터의저장과접근에대한제공은모델이담당하고, 화면표시는뷰, 이벤트의처리는컨트롤러가하도록각역할을구분한구조이다. 즉, 역할의분담을통하여상호간의영향을최소화하고각요소의독립성을보장하여독자

q 이장에서다룰내용 1 객체지향프로그래밍의이해 2 객체지향언어 : 자바 2

제8장 자바 GUI 프로그래밍 II

PowerPoint 프레젠테이션

쉽게 풀어쓴 C 프로그래밍

ch09

Chap12

쉽게 풀어쓴 C 프로그래밍

10-Java Applet

DB 에데이터저장을위한입력창설계 - JLabel, JTextField, JButton 을이용한입력창설계 - 2 -

PowerPoint Presentation

PowerPoint Presentation

PowerPoint Presentation

02 C h a p t e r Java

쉽게 풀어쓴 C 프로그래밊

<4D F736F F F696E74202D20C1A63038C0E520C5ACB7A1BDBABFCD20B0B4C3BC4928B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

11-GUI.key

Microsoft PowerPoint - Java7.pptx

Microsoft PowerPoint - 12장

PowerPoint 프레젠테이션

Microsoft Word - java19-1-final-answer.doc

09-interface.key

제11장 프로세스와 쓰레드

歯NetworkKawuiBawuiBo.PDF

PowerPoint 프레젠테이션

연습문제이론홀수정답

어댑터뷰

[ 그림 8-1] XML 을이용한옵션메뉴설정방법 <menu> <item 항목ID" android:title=" 항목제목 "/> </menu> public boolean oncreateoptionsmenu(menu menu) { getme

Cluster management software

Network Programming

Microsoft PowerPoint - lec09_12.ppt [호환 모드]

Transcription:

그래픽사용자인터페이스 그래픽사용자인터페이스이벤트객체, 리스너 그래픽사용자인터페이스 (Graphical User Interface, 간단히 GUI) 는컴포넌트들로구성된다. 514760-1 2016 년가을학기 11/10/2016 박경신 자바에서 GUI 의종류 AWT(Abatract Windows Toolkit) 운영체제가제공하는자원을이용하여서컴포넌트를생성한다. SWING 스윙컴포넌트가자바로작성되어있기때문에어떤플랫폼에서도일관된화면을보여줄수있다. AWT 와 SWING 컴포넌트 AWT 버전 스윙버전 버튼 Button JButton 레이블 Label JLabel 리스트 List JList 패스워드필드 없음 JPasswordField 슬라이더없음 JSlider

SWING 클래스계층구조 SWING 의특징 스윙 GUI 컴포넌트 형식화된텍스트입력이나패스워드필드동작과같은복잡한기능들이제공 자바 2D API 그림이나이미지, 애니메이션기능을제공 교체가능한룩앤필 (Look-and-Feel) 지원 데이터전송 자르기, 복사, 붙이기, 드래그앤드롭등의데이터전송기능제공 되돌리기 (undo) 와되풀이 (redo) 기능을손쉽게제공 스윙패키지 컨테이너와컴포넌트 기본컴포넌트 JButton, JLabel, JCheckbox, JChoice, JList, JMenu, JTextField, JScrollbar, JTextArea, JCanvas 등이여기에속한다. 컨테이너컴포넌트 다른컴포넌트를안에포함할수있는컴포넌트로서 JFrame, JDialog, JApplet, JPanel, JScrollPane 등이여기에속한다.

컨테이너의종류 최상위컨테이너 절대다른컨테이너안에포함될수없는컨테이너를의미한다. 프레임 (JFrame), 다이알로그 (JDialog), 애플릿 (JApplet) 등이여기에해당된다. 일반컨테이너 다른컨테이너안에포함될수있는컨테이너로패널 (JPanel), 스크롤페인 (JScrollPane) 등을의미한다. 프레임생성 #1 import javax.swing.*;.*; public class FrameTest { JFrame f = new JFrame("Frame Test"); f.setsize(300, 200); f.setdefaultcloseoperation(jframe. JFrame.EXIT_ON_CLOSE); f. JFrame 의객체생성 프레임생성 #2 import javax.swing.*;.*; Jframe을상속하여서 MyFrame을정의 public class MyFrame extends JFrame { setsize(300, 200); setdefaultcloseoperation(jframe. JFrame.EXIT_ON_CLOSE); settitle("myframe MyFrame"); public class MyFrameTest { MyFrame f = new MyFrame(); MyFrame 의객체생성 컴포넌트생성과추가 import javax.swing.*;.*; import java.awt.flowlayout; 배치관리자설정! public class MyFrame extends JFrame { setsize(300, 200); setdefaultcloseoperation(jframe. JFrame.EXIT_ON_CLOSE EXIT_ON_CLOSE); settitle("myframe MyFrame"); 컴포넌트생성및추가 setlayout(new FlowLayout()); JButton button = new JButton(" "); this.add.add(button); public class MyFrameTest { MyFrame f = new MyFrame();

JFrame 클래스 컨테이너는컴포넌트들을트리 (tree) 형태로저장한다. 최상위컨테이너는이트리의루트노드가된다. 최상위컨테이너는내부에콘텐트페인 (content pane) 을가지고있다. 여기에화면에보이는컴포넌트를저장한다. 최상위컨테이너에는메뉴바를추가할수있다. Jframe 클래스주요메소드 setlocation(x, y), setbounds(x, y, width, height), setsize(width, height) 프레임의위치와크기를설정한다. seticonimage(iconimage) 윈도우시스템에타이틀바, 태스크스위처에표시할아이콘을알려준다. settitle() 타이틀바의제목을변경한다. setresizable(boolean) 사용자가크기를조절할수있는지를설정한다. 기본컴포넌트 패널 (panel) 레이블 (label) 버튼 (button) 텍스트필드 (text field) 버튼의종류 JButton - 가장일반적인버튼 JCheckBox - 체크박스버튼 JRadioButton - 라디오버튼은그룹중하나의버튼만체크할수있다.

LAB: 온도변환기 public class TemperatureConverter { public static void main(string[] args) ) { JFrame f = new JFrame(); JPanel panel = new JPanel(); f.add.add(panel panel); JLabel label1 = new JLabel(" "); JLabel label2 = new JLabel(" "); JTextField field1 = new JTextField(15); JTextField field2 = new JTextField(15); JButton button = new JButton(" "); panel.add.add(label1 label1); panel.add.add(field1 field1); panel.add.add(label2 label2); panel.add.add(field2 field2); panel.add.add(button button); f.setsize.setsize(300, 150); f.setdefaultcloseoperation.setdefaultcloseoperation(jframe. JFrame.EXIT_ON_CLOSE EXIT_ON_CLOSE); f.settitle.settitle(" "); f.setvisible. LAB: 피자주문화면 패널안에다른패널이포함될수있다. 이것을이용하여서다음그림처럼프로그램의화면을디자인하라. 패널 패널 A 패널 B 프레임 public class MyFrame extends JFrame { setsize(600, 150); setdefaultcloseoperation(jframe.exit_on_close); settitle("myframe"); JPanel panel = new JPanel(); JPanel panela = new JPanel(); JPanel panelb = new JPanel(); JLabel label1 = new JLabel(".."); panela.add(label1); JButton button1 = new JButton(" "); JButton button2 = new JButton(" "); JButton button3 = new JButton(" "); panelb.add(button1); panelb.add(button2); panelb.add(button3); JLabel label2 = new JLabel(" "); JTextField field1 = new JTextField(10); panelb.add(label2); panelb.add(field1); panel.add(panela); panel.add(panelb); add(panel); setvisible( public class MyFrameTest { MyFrame f = new MyFrame(); 배치관리자의종류 FlowLayout GridBagLayout GridLayout

배치관리자의종류 배치관리자의설정 BorderLayout 1. 생성자를이용하는방법 JPanel panel = new JPanel(new BorderLayout()); 2. setlayout() 메소드이용 panel.setlayout(new FlowLayout()); BoxLayout CardLayout 프로그래머가컴포넌트의크기와힌트를배치관리자에게주고싶은경우에는 setminimumsize(), setpreferredsize(), setmaximumsize() 메소드를사용 button.setmaximumsize(new Dimension(300, 200)); // 최대크기힌트 button.setalignmentx(jcomponent.center_alignment); // 중앙정렬힌트 BorderLayout 클래스 GridLayout 클래스 생성자또는메소드 BorderLayout(int hgap, int vgap) 설명 컴포넌트사이의수평간격 hgap 과수직간격 vgap 을을가지는 BorderLayout 객체생성 생성자 GridLayout(int rows, int cols) 설명 rows 행과 cols 열을가지는 GridLayout 객체 를생성한다. 만약 rows 나 cols 가 0 이면필요 sethgap(int) 컴포넌트사이의수평간격설정 ( 단위는픽셀 ) 한만큼의행이나열이만들어진다. setvgap(int) 컴포넌트사이의수직간격설정 GridLayout(int rows, int cols, int hgap, int rows 행과 cols 열을가지는 GridLayout 객체를생성한다. hgap과 vgap은컴포넌트사이 vgap) 의수평간격과수직간격으로단위는픽셀이 다.

절대위치로배치하기 1. 배치관리자를 null 로설정한다. setlayout(null); 2. add() 메소드를사용하여컴포넌트를컨테이너에추가한다. Button b = Button("Absolute Position Button"); add(b); 3. setbounds() 메소드를사용하여절대위치와크기를지정한다. b.setbounds(x, y, w, h); 4. 컴포넌트의 repaint() 메소드를호출한다. b.repaint(); import java.awt.*; import java.awt.event.*; import javax.swing.*; class MyFrame extends JFrame { JButton b1; private JButton b2, b3; settitle("absolute Position Test"); setdefaultcloseoperation(jframe.exit_on_close); setsize(300, 200); JPanel p = new JPanel(); p.setlayout(null null); b1 = new JButton("Button #1"); p.add(b1); b2 = new JButton("Button #2"); p.add(b2); b3 = new JButton("Button #3"); p.add(b3); b1.setbounds(20, 5, 95, 30); b2.setbounds(55, 45, 105, 70); b3.setbounds(180, 15, 105, 90); add(p); public class AbsoluteTest { public static void main(string args[]) { MyFrame f=new MyFrame(); public class Calculator extends JFrame { private JPanel panel; private JTextField tfield; private JButton[] buttons; private String[] labels = { "Backspace", "", "", "CE", "C", "7", "8", "9", "/", "sqrt sqrt", "4", "5", "6", "x", "%","1" "1", "2", "3", "-", "1/x", "0", "+/-", ".", "+", "=" ; public Calculator() { tfield = new JTextField(35); panel = new JPanel(); tfield.settext.settext("0." "0."); tfield.setenabled.setenabled(false false); panel.setlayout.setlayout(new GridLayout(0, 5, 3, 3)); buttons = new JButton[25]; int index = 0; for (int rows = 0; rows < 5; rows++) { for (int cols = 0; cols < 5; cols++) { buttons[index index] ] = new JButton(labels labels[index index]); if( cols >= 3 ) buttons[index index]. ].setforeground setforeground(color. Color.red red); else buttons[index index]. ].setforeground setforeground(color. Color.blue blue); buttons[index index]. ].setbackground setbackground(color. Color.yellow yellow); panel.add.add(buttons buttons[index index]); index++; add(tfield tfield, BorderLayout.NORTH NORTH); add(panel panel, BorderLayout.CENTER CENTER); pack(); public static void main(string args[]) { Calculator s = new Calculator(); 이벤트 - 구동프로그래밍 이벤트 - 구동프로그래밍 (event-driven programming): 프로그램의실행이이벤트의발생에의하여결정되는방식

이벤트처리과정 이벤트리스너 발생된이벤트객체에반응하여서이벤트를처리하는객체를이벤트리스너 (event listener) 라고한다. 이벤트처리과정 1. 이벤트리스너클래스를작성한다. class MyListener implements ActionListener { public void actionperformed(actionevent e) { 이벤트객체 EventObject 클래스를상속받는다. Ex: MouseEvent 클래스 // Action. 2. 이벤트리스너를이벤트소스에등록한다. public class MyFrame extends JFrame { // 생성자에서컴포넌트를생성하고추가한다. button = new JButton(" 동작 ); button.addactionlistener(new MyListener()); // 버튼생성 이벤트리스너를컴포넌트에붙인다. 이벤트를발생시킨이벤트소스등의여러가지정보를제공한다. public void actionperformed(actionevent e) { button = (JButton)e.getSource();

이벤트처리기작성방법 1. 독립적인클래스로이벤트처리기를작성 2. 내부클래스로이벤트처리기를작성 3. 프레임클래스에이벤트처리를구현 4. 무명클래스를사용하는방법 5. 람다식을이용하는방법 독립적인클래스작성 import javax.swing.*; import java.awt.event.*;.*; class MyListener implements ActionListener { public void actionperformed(actionevent e) { JButton button = (JButton) e.getsource(); button.settext("."); class MyFrame extends JFrame { private JButton button; private JLabel label; 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); public class ActionEventTest1 { this.add(panel); this.setvisible( MyFrame t = new MyFrame(); 내부클래스방법 만약 MyListener 라는클래스를별도의클래스로하면 MyFrame 안의멤버변수들을쉽게사용할수없다. 일반적으로 MyListener 클래스를내부클래스로만든다. MyFrame 에서이벤트도처리하는방법 더많이사용되는방법은 MyFrame 클래스가 JFrame 을상속받으면서동시에 ActionListener 인터페이스도구현하는경우이다. class MyFrame extends JFrame { private class MyListener implements ActionListener { public void actionperformed(actionevent e) { if (e.getsource() == button) { label.settext("."); public class ActionEventTest { MyFrame t = new MyFrame(); 내부클래스 label 에접근할 수있다. class MyFrame extends JFrame implements ActionListener { button = new JButton(" "); label = new JLabel(" "); button.addactionlistener(this public void actionperformed(actionevent e) { if (e.getsource ( e.getsource() == button) { label.settext(" ("."); 이벤트도처리

무명클래스를사용하는방법 람다식을이용하는방법 class MyFrame extends JFrame { button = new JButton(" "); button.addactionlistener(new ActionListener() { public void actionperformed(actionevent e) { if (e.getsource ( e.getsource() == button) { label.settext(" ("."); ); 안드로이드에서많이사용된다! import javax.swing.*; class MyFrame extends JFrame { private JButton button; private JLabel label; 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. LAB: 키패드만들기 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 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 new Dimension(100, 100)); panel.add(btn); pack(); setdefaultcloseoperation(exit_on_close); public void actionperformed(actionevent e) { String actioncommand = e.getactioncommand(); txt.settext(txt.gettext() + actioncommand); new KeyPad(); LAB: 퍼즐게임 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 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]); for(int i=0; i<9; i++) buttons[i].addactionlistener(this add(panel, BorderLayout.CENTER); reset = new MyButton("reset"); reset.setbackground(color.red); reset.setforeground(color.yellow); add(reset, BorderLayout.SOUTH);

// reset.addactionlistener( setsize(300, 300); setdefaultcloseoperation(jframe.exit_on_close); public void actionperformed(actionevent e) { MyButton b = (MyButton) e.getsource(); if( b.gettext().equals(" ")==true 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(" "); 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(" "); new Puzzle(); LAB: 가위바위보게임 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 new GridLayout(0, 3)); information = new JTextField("!"); output = new JTextField(20); 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); RockPaperScissor gui = new RockPaperScissor(); 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) output.settext(" "); else if (computer == PAPER) output.settext(" "); else output.settext(" "); else if (e.getsource() == scissor) { if (computer == PAPER) output.settext(" "); else if (computer == SCISSOR) output.settext(" "); else output.settext(" "); 이벤트의분류 스윙컴포넌트에의하여지원되는이벤트는크게두가지의카테고리로나누어진다.

저수준이벤트 의미적이벤트 Action 이벤트 사용자가버튼을클릭하는경우 사용자가메뉴항목을선택하는경우 사용자가텍스트필드에서엔터키를누르는경우 액션이벤트예제 두개의버튼을만들어서패널의배경색을변경하는프로그램을작성하여보자. 이벤트리스너는하나만생성한다. class MyFrame extends JFrame { private JButton button1; private JButton button2; private JPanel panel; this.setsize(300, 200); this.setdefaultcloseoperation(jframe.exit_on_close); this.settitle(" "); panel = new JPanel(); button1 = new JButton(" "); button1.addactionlistener(new new MyListener()); panel.add(button1); button2 = new JButton(" "); button2.addactionlistener(new new MyListener()); panel.add(button2); this.add(panel); this.

액션이벤트예제 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 { MyFrame t = new MyFrame(); 이벤트발생원의식별 getsource() 메소드를이용하여이벤트를발생시킨객체를식별한다. getid() 메소드를이용하여이벤트의타입을식별한다. getactioncommand() 메소드를이용하여이벤트를발생시킨컴포넌트이름을식별한다. public void actionperformed(actionevent e) { if (e.getsource () == button1){ Key 이벤트 Key 이벤트예제 KeyListener 인터페이스구현 메소드 keytyped(keyevent e) keypressed(keyevent e) keyreleased(keyevent e) 설명 사용자가글자를입력했을경우에호출 사용자가키를눌렀을경우에호출 사용자가키에서손을떼었을경우에호출 키보드에서문자가입력되면문자코드와키코드, 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( settitle("keyevent Test"); setsize(400, 200); setvisible( new KeyEventTest();

Key 이벤트예제 자동차게임예제 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"); 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 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()); CarGameTest s = new CarGameTest(); LAB: 신호등 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);

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 { add(new MyPanel()); setsize(300, 500); public static void main(string[] arg) { new MyFrame(); Mouse 이벤트 MOUSELISTENER 인터페이스 마우스이벤트순서 1. Mouse pressed (# of clicks: 1) X=118 Y=81 2. Mouse released (# of clicks: 1) X=118 Y=81 3. Mouse clicked (# of clicks: 1) X=118 Y=81

MOUSEMOTIONLISTENER 인터페이스 Mouse 이벤트예제 import javax.swing.*; import java.awt.*; import java.awt.event.*; class MyFrame extends JFrame implements MouseListener, MouseMotionListener { settitle("mouse Event"); setsize(300, 200); setdefaultcloseoperation(jframe.exit_on_close); JPanel panel = new JPanel(); panel.addmouselistener( panel.addmousemotionlistener( add(panel); setvisible( protected void display(string s, MouseEvent e) { System.out.println(s + " X=" + e.getx() + " Y=" + e.gety()); 마우스이벤트처리기를붙인다. 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); public void mousedragged(mouseevent e) { display("mouse dragged", e); public void mousemoved(mouseevent e) { display("mouse moved", e); public class MyFrameTest5 { 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 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) { );

자동차게임예제 ( 수정 ) LAB: 사각형그리기 public void paintcomponent(graphics g) { super.paintcomponent(g); g.drawimage(img, img_x, img_y, null); public class MyFrame extends JFrame { add(new MyPanel()); setsize(300, 500); public static void main(string[] arg) { new MyFrame(); 마우스를클릭할때마다사각형이화면에그려지는예제를작성하여보자. 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( 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); @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(); @Override public void mousereleased(mouseevent e) { @Override public void mouseclicked(mouseevent e) { @Override public void mouseentered(mouseevent e) { @Override 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( MouseEventTest s = new MouseEventTest(); LAB: 그림그리기 이번에는마우스로화면에그림을그리는프로그램을작성하여보자. 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();

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()); Scribble s = new Scribble(); Adapter 클래스 인터페이스의경우, 모든메소드를구현하여야한다. 어댑터클래스 (Adaptor Class) 를사용하면원하는메소드만을구현하는것이가능해진다 인터페이스 ComponentListener ContainerListener FocusListener KeyListener MouseListener MouseMotionListener WindowListener 어댑터클래스 ComponentAdapter ContainerAdapter FocusAdater KeyAdapter MouseAdapter MouseMotionAdapter WindowAdapter Listener 를사용하는경우 Adapter 를사용하는경우 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 new MouseAdapter() { public void mousepressed(mouseevent e) { img_x = e.getx(); img_y = e.gety(); repaint(); ); LAB: 카운터 버튼을누르면카운터값이하나씩증가되어화면표시된다. 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 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");