13. Advanced GUI Components

Slides:



Advertisements
Similar presentations
CSE 341, S. Tanimoto Java-AWT- 1 A Brief Overview of the Abstract Windowing Toolkit (AWT) Motivation. Typical Frame setup. BorderLayout, FlowLayout, GridLayout.
Advertisements

Managing Input Events in Swing Week 5 Workshop Lyn Bartram.
Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 12 Event-Driven Programming 找出画中真谛 — 保罗. 塞尚.
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.
Mouse Events and Keyboard Events
OOP&M - theory lectures1 OOP&M – the sixth day “… there must be a secret out there …” - Spok -
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.
Events ● Anything that happens in a GUI is an event. For example: – User clicks a button, presses return when typing text, or chooses a menu item ( ActionEvent.
Event Handling n Events: an event is an object that describes a state change in a source. n Event Sources: A source is an object that generates an event.
1 Gui Programming (Part I) Graphical User Interfaces (Part I) l Introduction to events. l A Brief history. l Event sources and listeners. l The delegation.
Intermediate Java1 An example that uses inner classes Week Four Continued.
Graphical User Interfaces (GUI) Abstract Windows Toolkit (AWT): java.awt GUI elements: Primitive Button, Label, Checkbox, Scrollbar, etc. Container Panel,
1 lecture 12Lecture 13 Event Handling (cont.) Overview  Handling Window Events.  Event Adapters Revisited.  Introduction to Components and Containers.
28-Aug-15 Air Force Institute of Technology Electrical and Computer Engineering Object-Oriented Programming Design Topic : Event Handling – GUI Part II.
Mouse Events. Handling Mouse Events Java provides two listener interfaces to handle mouse events: MouseListener;  MouseListener;  MouseMotionListener.
Graphical User Interface CSI 1101 N. El Kadri. Plan - agenda Graphical components Model-View-Controller Observer/Observable.
More Event Handling Adapters Anonymous Listeners Pop menus Validating User Input.
Cs884(Prasad)java12AWT1 Abstract Windowing Toolkit Support for Graphical User Interface (Event-driven programming)
GUI 프로그래밍과 AWT(2) 컴퓨터 공학실험 (I) 인공지능 연구실. 2 AWT Event Model  Java 의 Event Model 1.Event : 사용자가 Program 에 가한 행동 2.Event Source : Event 가 일어난 근원 3.Event.
CompSci 230 S Software Construction Applets & AWT.
Pravin Yannawar, DOCS, NMU Jalgaon. Basic Java : Event handling in AWT and Swing 2 Objectives of This Session Explain the Event handling mechanism & demonstrate.
Event Handling. Event Driven Programming Flow of programs is determined by events. The Operating system recognizes events and passes them to the particular.
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.
Universidad Nacional de Colombia Facultad de Ingeniería Departamento de Sistemas ertificación en AVA.
© Marty Hall, Larry Brown Web core programming 1 Handling Mouse and Keyboard Events.
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.
Chapter 14 – Using Layout Managers and Events Dr. James Burns –
Ch13 Creating windows and applets. Short overview AWT (Abstract Windowing Toolkit) Early Java development used graphic classesEarly Java development used.
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.
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.
Laboratory Study November, Demonstrates Life Cycle of an Applet + Mouse Events + Scrolling.
Chapter 6: Events in Java 1.0 Model –Event class –selecting component to handle –handleEvent method –helper methods (action, keyUp, mouseUp, etc.) 1.1.
2/17/2016 DEPT OF CSE 1 EVENT HANDLING. 2/17/2016 DEPT OF CSE 2 Event handling is at the core of successful applet programming There are several types.
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.
Event Listeners ActionListener –button,list AdjustmentListener-scroll bar ComponentListener-when component hidden…. ContainerListener-comp added or removed.
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.
Event Handling and Listeners in SWING The practice of event handling.
Sep 181 Example Program DemoTranslateEnglishGUI.java.
1CS480: Graphical User Interfaces. Dario Salvucci, Drexel University. Lecture 6: Event-Driven Programming.
어서와 Java는 처음이지! 제10장 이벤트 처리.
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는 처음이지! 제10장 이벤트 처리.
CSC 205 Programming II Lecture 5 AWT - I.
Chapter 14 Event-Driven Programming
Lecture 8 Object Oriented Programming Using Java
Programming in Java, 2e Sachin Malhotra Saurabh Choudhary.
CHAPTER Reacting to the user.
Chapter 12 Event-Driven Programming
Programming in Java Sachin Malhotra, Chairperson, PGDM-IT, IMS Ghaziabad Saurabh Chaudhary, Dean, Academics, IMS Ghaziabad.
Handling User Events with Swing
Event Handling Chapter 2 Objectives
Computer Science 209 Graphics and GUIs.
GUI Programming III: Events
CSE Software Engineering Fall 1999 Updated by J. Brown
Event-driven programming for GUI
Unit I: Chapter 1 Event handling.
CHAPTER 2 Event Handling.
Web Design & Development Lecture 12
A Brief Overview of the Abstract Windowing Toolkit (AWT)
Chapter 16 Event-Driven Programming
A Brief Overview of the Abstract Windowing Toolkit (AWT)
A Brief Overview of the Abstract Windowing Toolkit (AWT)
Programming Graphical User Interface (GUI)
Presentation transcript:

13. Advanced GUI Components

13. JAVA GUI 13.1 GUI의 기본 요소 13.1.1 Canvas(캔버스) - 이미지 파일을 읽어서 디스플레이 - 이미지 파일을 읽어서 디스플레이 - 선이나 도형과 같은 그래픽 요소를 그리는 작업 생성자 public Canvas()

13. JAVA GUI [예제 프로그램] import java.awt.*; import java.applet.*; [예제 프로그램] import java.awt.*; import java.applet.*; public class CanvasDemo extends Applet {    public void init() {    super.init();               // Applet의 init() 메소드 호출    setLayout(new GridLayout(1,1));    resize(350,200);    MyCanvas c = new MyCanvas();    add(c);   // 새로운 캔버스를 현 애플릿에 추가함    } } class MyCanvas extends Canvas {    public void paint(Graphics g) {    g.setColor(Color.green);    g.fillOval(30,80,180,120);    g.drawLine(10,10,280,150);    g.fillRect(140,10,180,60);    } }

13. JAVA GUI 13.1.2 Panel - Panel은 Container로서, GUI 컴포넌트들을 묶어 주는 역할 - Panel안에 포함된 컴포넌트들을 별도의 Layout 사용  - Component 클래스와 Container 클래스의 후손 클래스 생성자 ① public Panel() - 패널을 생성한다. ② public Panel(LayoutManger layout) - 생성된 패널의 레이아웃 형식을 지정할 수 있다.

13. JAVA GUI [자바 예제 소스] import java.applet.*; import java.awt.*; [자바 예제 소스] import java.applet.*; import java.awt.*; public class PanelDemo extends Applet {   public void init() {    setLayout(new BorderLayout(2,4));    TextField tf = new TextField(20);     add(tf, BorderLayout.NORTH); //텍스트필드는 북쪽에 추가된다.    Panel c = new Panel(new GridLayout(2,3)); // 새로운 panel 생성      c.add(new Button("1"));  // 다음 버튼들은 panel에 주가됨      c.add(new Button("2"));      c.add(new Button("3"));      c.add(new Button("4"));      c.add(new Button("5"));      c.add(new Button("6"));      c.setBackground(Color.yellow);  //panel의 백그라운드 색 지정    add(c, BorderLayout.CENTER); //panel을 애플릿의 가운데에 부착

13. JAVA GUI [자바 예제 소스]  Panel e = new Panel(new GridLayout(2,1)); // 새로운 panel 생성         e.add(new Button("+"));           // 다음 버튼들은 panel에 추가됨         e.add(new Button("="));         e.setBackground(Color.white);         add(e, BorderLayout.EAST);         } }

13. JAVA GUI [예제 프로그램] import java.applet.Applet; import java.awt.*; [예제 프로그램] import java.applet.Applet; import java.awt.*; import java.awt.event.*; public class Canvas2 extends Applet implements ActionListener {    private Panel p;    private CustomCanvas c;    private Button circle, square;    public void init()    {  c = new CustomCanvas();  // 캔버스를 생성하여 녹색 지정       c.setBackground( Color.green );       square = new Button( "Square" ); // Square 버튼 생성       square.addActionListener(this);       circle = new Button( "Circle" ); // Circle 버튼 생성       circle.addActionListener(this);       p = new Panel();       p.setLayout( new GridLayout( 2, 1 ) );       p.add( circle ); // panel p에 “circle" 버튼 추가       p.add( square );      // panel p에 “square" 버튼 추가

13. JAVA GUI [예제 프로그램] setLayout( new BorderLayout() ); [예제 프로그램] setLayout( new BorderLayout() );       add( p, BorderLayout.WEST );      // 애플릿에 panel p 추가       add( c, BorderLayout.CENTER );    // 애플릿에 canvas c 추가    }    public void actionPerformed(ActionEvent e)    {   String cmd = e.getActionCommand();        if(cmd.equals("Square")) {                c.draw(CustomCanvas.SQUARE);        }        else { c.draw(CustomCanvas.CIRCLE);        }    } } class CustomCanvas extends Canvas {    public final static int CIRCLE = 1, SQUARE = 2;    private int shape;    public void paint( Graphics g )    {  if ( shape == CIRCLE )          g.fillOval( 50, 10, 60, 60 );      else if ( shape == SQUARE )          g.fillRect( 50, 10, 60, 60 );    }    public void draw( int s )    {       shape = s;       repaint();    } }

13. JAVA GUI 13.2 이벤트 처리 모델 13.2.1 이벤트(event) 다음의 사용자 행위가 이벤트에 해당 13.2 이벤트 처리 모델 13.2.1 이벤트(event) 다음의 사용자 행위가 이벤트에 해당 ① 마우스 클릭  ② 마우스 이동 ③ 키보드 입력 ④ 사용자 인터페이스 이벤트

13. JAVA GUI 13.3 자바 1.1 이후 버전의 이벤트 처리 처리를 원하는 이벤트를 리스너 객체에 등록 (예) 13.3 자바 1.1 이후 버전의 이벤트 처리 처리를 원하는 이벤트를 리스너 객체에 등록 (예)   public class buttonDemo extends Applet                 implement ActionListener { // ActionListener 구현    public void init() {       Button b1;        b1 = new Button("One");        b1.addActionListener(this);  // 액션 이벤트 등록        ...    }   }

13.3.1 이벤트의 종류와 처리

13. JAVA GUI 13.3.2 ActionEvent의 처리 - ActionEvent의 처리 ① 버튼: 마우스로 버튼을 클릭 ② 리스트: 마우스로 리스트에 있는 아이템을 더블 클릭 ③ MenuItem: 마우스로 메뉴를 선택 ④ 텍스트 필드: 텍스트 필드에서 엔터 키 입력

13. JAVA GUI [ActionEvent를 처리 예제 프로그램] public class ActionEvent1 extends java.applet.Applet     implements ActionListener {   Button b1, b2;   TextField t1;   List t2;   Panel p;   String msg = "";   public void init() {    setLayout(new BorderLayout());        p = new Panel(new GridLayout(2, 2, 4, 2));    b1 = new Button("First");    b2 = new Button("Second");    t1 = new TextField(10);    t2 = new List(3, true);      t2.add("memory");  // List t2에 item 추가      t2.add("disk");      t2.add("CPU");      t2.add("monitor");      t2.add("printer");

13. JAVA GUI [ActionEvent를 처리 예제 프로그램] b1.addActionListener(this);    t1.addActionListener(this);    t2.addActionListener(this);    p.add(b1);  p.add(t1);    p.add(b2);  p.add(t2);    add(p, BorderLayout.NORTH);   }   public void actionPerformed(ActionEvent e) {    msg = e.getActionCommand();    repaint();   public void paint(Graphics g) {    g.drawString(msg, 20, 150); }

13. JAVA GUI 13.3.3 Adjustment 이벤트 -스크롤 바 및 ScrollPane 객체에서 현재값이 바뀌게 될때 발생 -이벤트 처리는 AdjustmentListener 구현 클래스의   adjustmentValueChanged(AdjustmentEvent e) 사용 class MyListener implements AdjustmentListener {    public void adjustmentValueChanged(AdjustmentEvent e) {    ...... // 이벤트 발생시, 수행할 코드    } }

13. JAVA GUI [Adjustment 이벤트 처리 예제] public class AdjustmentEventDemo        extends java.applet.Applet {   int h = Scrollbar.HORIZONTAL;   int v = Scrollbar.VERTICAL;   TextField tf = new TextField(28);   Scrollbar s1 = new Scrollbar(h, 0, 10, 0, 400);   Scrollbar s2 = new Scrollbar(v, 0, 10, 0, 100);     public void init() {    setLayout(new BorderLayout());    add(tf, BorderLayout.CENTER);    add(s1, BorderLayout.SOUTH);    add(s2, BorderLayout.EAST);        s1.addAdjustmentListener(new MyListener());    s2.addAdjustmentListener(new MyListener());

13. JAVA GUI [Adjustment 이벤트 처리 예제] class MyListener implements AdjustmentListener {    public void adjustmentValueChanged(AdjustmentEvent e) {            Scrollbar sbar = (Scrollbar) e.getAdjustable();      int e_type = e.getAdjustmentType();      int val = e.getValue();      String msg ="";      switch(e_type) {       case AdjustmentEvent.TRACK:         msg = "Track Event ";         break;       case AdjustmentEvent.BLOCK_INCREMENT:         msg = "Block Inc ";         break;       case AdjustmentEvent.BLOCK_DECREMENT:         msg = "Block Dec ";         break;       case AdjustmentEvent.UNIT_INCREMENT:         msg = "UNIT Inc ";         break;       case AdjustmentEvent.UNIT_DECREMENT:         msg = "UNIT Dec ";      }

13. JAVA GUI [Adjustment 이벤트 처리 예제] if(sbar == s1) {     tf.setText("horizontal bar: Event = " + msg + "Value=" + val);    }   else { tf.setText("vertical bar: Event = " + msg + "Value=" + val); }   } }

13. JAVA GUI 13.3.4 ItemEvent의 처리 - checkbox, choice, list 객체에서 항목을 선택시 발생 - ItemListener 인터페이스를 구현 클래스가 처리 - ItemStateChanged(ItemEvent e)를 사용 class MyListener implements ItemListener {    public void itemStateChanged(ItemEvent e) {      ... // 이벤트 발생시, 수행할 코드    } }

13. JAVA GUI [ItemEvent 처리 예제] public class ItemEventDemo extends Applet implements ItemListener {    Checkbox  ch1, ch2;    Choice    c1;    List st;    TextField tf;     String  msg = "";    public void init() {        setLayout(new GridLayout(3, 2));        ch1 = new Checkbox("One");        ch1.addItemListener(this);        ch2 = new Checkbox("Two");        ch2.addItemListener(this);        add(ch1);     add(ch2);        lst = new List(2, false);        lst.addItemListener(this);        lst.add("Pentium 100");        lst.add("Pentium 200");        lst.add("Celoron 333");        lst.add("Pentium II");        lst.add("Pentium III");        add(lst);

13. JAVA GUI [ItemEvent 처리 예제] c1 = new Choice();        c1.addItemListener(this);        c1.add("Memory");   c1.add("Printer");        c1.add("CPU");               c1.add("Disk");        add(c1);        tf = new TextField(18);     add(tf);    }    public void itemStateChanged(ItemEvent e) {        if(e.getItemSelectable() instanceof List)          msg = "List: ";        else if (e.getItemSelectable() instanceof Choice)          msg = "Choice: ";        else         {  msg = "CheckBox: ";          if(e.getStateChange()==ItemEvent.SELECTED)               msg += "selected ";          else msg += "de-selected "; }        msg = msg + e.getItem();        tf.setText(msg);    }}

13. JAVA GUI 13.3.5 마우스 이벤트 1) 마우스 클릭과 관련된 이벤트를 처리 13.3.5 마우스 이벤트 1) 마우스 클릭과 관련된 이벤트를 처리 ☞ MouseListener 인터페이스를 구현 ☞ MouseAdapter 클래스를 상속 2) 마우스 이동에 관련된 이벤트를 처리 ☞ MouseMotionListener 인터페이스 구현 ☞ MouseMotionAdapter 클래스를 상속

13. JAVA GUI MouseEvent 클래스에서 지원되는 메소드 ① public void mousePressed(MouseEvent e) - 마우스 커서가 컴포넌트 안에 있을 때 마우스 버튼을 눌렀을 때 - 이벤트 id: MOUSE_PRESSED ② public void mouseClicked(MouseEvent e) - 마우스 커서를 컴포넌트 안에 정지시키고, 버우스 버튼을 클릭하였을 때 - 이벤트 id: MOUSE_CLICKED ③ public void mouseReleased(MouseEvent e) - 마우스를 drag한 후, 눌렀던 마우스 버튼을 놓았을 때 - 이벤트 id: MOUSE_RELEASED ④ public void mouseEntered(MouseEvent e) - 마우스 커서가 컴포넌트 안으로 이동하였을 때 - 이벤트 id: MOUSE_ENTERED

13. JAVA GUI MouseEvent 클래스에서 지원되는 메소드 ⑤ public void mouseExited(MouseEvent e) - 마우스 커서가 컴포넌트 밖으로 이동하였을 때 - 이벤트 id: MOUSE_EXITED MouseMotionEvent의 메소드 ① public void mouseDragged(MouseEvent e) - 마우스 버튼을 누르고 마우스를 이동할 때 - 이벤트 id: MOUSE_DRAGGED ② public void mouseMoved(MouseEvent e) - 마우스가 이동하였을 때 - 이벤트 id: MOUSE_MOVED

13. JAVA GUI [마우스 이벤트를 처리하는 예제] [마우스 이벤트를 처리하는 예제] public class MouseEventDemo1 extends java.applet.Applet {   TextField tf; public void init() {    setLayout(new BorderLayout());    Canvas canvas = new Canvas();    add(canvas, BorderLayout.CENTER);    canvas.addMouseListener(new mouseListener());    canvas.addMouseMotionListener(new mouseMotionListener());    tf = new TextField();    add(tf, BorderLayout.SOUTH);     } class mouseListener implements MouseListener { // 내부클래스 정의    public void mouseClicked(MouseEvent e) {     if(e.getModifiers()==InputEvent.BUTTON1_MASK)       tf.setText("Left button Click : " + e.getX() + " , " + e.getY());     else     tf.setText("Right  button Click : " + e.getX() + " , " + e.getY());  }

13. JAVA GUI [마우스 이벤트를 처리하는 예제] [마우스 이벤트를 처리하는 예제] public void mouseEntered(MouseEvent e) {      tf.setText("Mouse Enter : " + e.getX() + " , " + e.getY());     } public void mouseExited(MouseEvent e) {      tf.setText("Mouse Exit : " + e.getX() + " , " + e.getY());       } public void mousePressed(MouseEvent e) {      tf.setText("Mouse Press : " + e.getX() + " , " + e.getY());      } public void mouseReleased(MouseEvent e) {      tf.setText("Mouse Release : " + e.getX() + " , " + e.getY());    }     } class mouseMotionListener implements MouseMotionListener {   public void mouseDragged(MouseEvent e) {      tf.setText("Mouse Drag : " + e.getX() + " , " + e.getY());         }   public void mouseMoved(MouseEvent e) {             tf.setText("Mouse Move : " + e.getX() + " , " + e.getY());         } } }

13. JAVA GUI

13. JAVA GUI 13.3.6 키 이벤트 - KeyEvent는 키보드로부터 입력이 일어날 때 발생 지원되는 상수값 13.3.6 키 이벤트 - KeyEvent는 키보드로부터 입력이 일어날 때 발생 지원되는 상수값 KeyEvent.KEY_PRESSED  키가 눌러 졌을 때 KeyEvent.KEY_RELEASED 눌렀던 키를 놓았을 때 KeyEvent.KEY_TYPED     문자가 타이핑되었을 때    컴포넌트에서 발생하는 키 이벤트를 처리하기 위해서는 KeyListener 인터페이스를 구현하여야 한다. KeyListener에 등록된 GUI 컴포넌트에서 키 이벤트가 발생 시에 다음의 메소드를 호출하게 된다. ① void keyPressed(KeyEvent e) - 키보드에서 키를 눌렀을 때 ② void keyReleased(KeyEvent e) - 눌렀던 키를 놓았을 때 ③ void keyTyped(KeyEvent e) - 키보드에서 문자를 타이핑하였을 때

13. JAVA GUI 13.3.6 키 이벤트 o KeyEvent 클래스에서 지원되는 메소드 13.3.6 키 이벤트 o KeyEvent 클래스에서 지원되는 메소드 ① public int getKeyCode() -  키코드 값을 반환한다. ② public char getKeyChar() -  키보드 문자를 반환한다.

13. JAVA GUI [키보드 이벤트 처리 예제] import java.awt.*; [키보드 이벤트 처리 예제] import java.awt.*; import java.awt.event.*; import java.applet.Applet; public class KeyEvent1 extends Applet implements KeyListener {    private String line1 = "";    private String line2 = "";    public void init()    {  addKeyListener( this );  // 애플릿을 키 리스너에 등록       requestFocus();   }    public void paint( Graphics g )    {  g.drawString( line1, 25, 30 );       g.drawString( line2, 25, 48 );   }    public void keyPressed( KeyEvent e )    {  line1 = "Key pressed: " + e.getKeyText( e.getKeyCode() );       setLines2( e );   }    public void keyReleased( KeyEvent e )    {  line1 = "Key released: " + e.getKeyText( e.getKeyCode() );       setLines2( e ); }

13. JAVA GUI [키보드 이벤트 처리 예제] public void keyTyped( KeyEvent e ) [키보드 이벤트 처리 예제] public void keyTyped( KeyEvent e )    {  line1 = "Key typed: " + e.getKeyChar();       setLines2( e );   }    private void setLines2( KeyEvent e )    {  String temp =  e.getKeyModifiersText( e.getModifiers() );       line2 = "Modifier keys pressed: " +           ( temp.equals( "" ) ? "none" : temp );       repaint();    } }

13. JAVA GUI 13.3.7 컴포넌트 이벤트(ComponentEvent) 때 또는 크기가 조정될 때 발생하는 이벤트 - 지원되는 상수 COMPONENT_HIDDEN 컴포넌트가 감추어 질 때 COMPONENT_SHOWN 컴포넌트가 다시 나타날 때 COMPONENT_MOVED 컴포넌트가 이동하였을 때 COMPONENT_RESIZED 컴포넌트의 크기가 변하였을 때 - 지원되는 메소드    ① public Component getComponent()    컴포넌트 이벤트를 발생시킨 컴포넌트를 반환한다.

13. JAVA GUI 13.3.7 컴포넌트 이벤트(ComponentEvent) o 컴포넌트 이벤트 처리 - 지원되는 메소드 - 지원되는 메소드 ① void componentHidden(ComponentEvent e)    컴포넌트가 감추졌을 때 호출된다. ② void componentShown(ComponentEvent e)    컴포넌트가 나타났을 때 호출된다. ③ void componentMoved(ComponentEvent e)    컴포넌트가 이동하였을 때 호출된다. ④ void componentResized(ComponentEvent e)    컴포넌트의 크기가 변경되었을 때 호출된다. o  컴포넌트 이벤트를 처리하는 클래스의 형식    class My_Component_Handler implements ComponentListener {        public void componentHidden(ComponentEvent e)  {        // 컴포넌트가 감추어졌을 때 실행할 코드        }        public void componentShown(ComponentEvent e)  {        // 컴포넌트가 나타났을 때 실행할 코드         }        public void componentMoved(ComponentEvent e)  {        // 컴포넌트가 이동하였을 때 실행할 코드        }        public void componentResized(ComponentEvent e)  {        // 컴포넌트의 크기가 변경되었을 때 실행할 코드   } }

13. JAVA GUI 13.3.9 윈도우 이벤트 - 지원되는 상수 WINDOW_ACTIVATED 윈도우가 활성화될 때 13.3.9 윈도우 이벤트 - 지원되는 상수    WINDOW_ACTIVATED 윈도우가 활성화될 때    WINDOW_CLOSED 윈도우가 닫힐 때    WINDOW_CLOSING  사용자가 윈도우를 닫으려 할 때    WINDOW_ICONIFIED 윈도우가 아이콘으로 될 때    WINDOW_OPENED 윈도우가 열릴 때 o 윈도우 이벤트의 처리 - WindowListener 인터페이스 구현 클래스 정의 - addWindowListener() 메소드 사용하여 등록

13. JAVA GUI 13.3.9 윈도우 이벤트 o 지원되는 메소드 13.3.9 윈도우 이벤트 o 지원되는 메소드 ① void windowActivated   (WindowEvent e)    윈도우가 활성화되었을 때 호출된다. ② void windowClosed(WindowEvent e)    윈도우가 닫혔을 때 호출된다. ③ void windowClosing(WindowEvent e)    윈도우를 닫으려 할 때 호출된다. ④ void windowDeactivated(WindowEvent e)    윈도우가 비활성화되었을 때 호출된다. ⑤ void windowDeiconified(WindowEvent e)    윈도우가 아이콘에서 원래 상태로 되돌아왔을 때 호출된다. ⑥ void windowIconified(WindowEvent e)    윈도우가 아이콘으로 변경되었을 때 호출된다. ⑦ void windowOpened(WindowEvent e)    윈도우가 열렸을 때 호출된다.

13. JAVA GUI 13.3.9 윈도우 이벤트 o 윈도우 이벤트 처리 형식 13.3.9 윈도우 이벤트 o 윈도우 이벤트 처리 형식    class My_window_handler implement WindowListener {        public void windowActivated(WindowEvent e) {        // 윈도우가 활성화되었을 때 실행할 코드       }        public void windowClosed(WindowEvent e) {        // 윈도우가 닫혔을 때 실행할 코드        }        public void windowClosing(WindowEvent e) {        // 윈도우가 닫으려고 할 때 실행할 코드     }        public void windowDeactivated(WindowEvent e) {        // 윈도우가 비 활성화되었을 때 실행할 코드      }        public void windowDeiconified(WindowEvent e) {        // 윈도우가 아이콘에서 본래 상태로 돌아왔을 때 실행할 코드 }        public void windowIconified(WindowEvent e) {        // 윈도우가 아이콘으로 되었을 때 실행할 코드      }        public void windowOped(WindowEvent e) {        // 윈도우가 열렸을 때 실행할 코드       }    }

13. JAVA GUI [윈도우이벤트 예제 프로그램] import java.awt.*; [윈도우이벤트 예제 프로그램] import java.awt.*; import java.awt.event.*; class Frame1 extends Frame {   Frame1(String title) {     super(title);     addWindowListener(new WindowAdapter() {       public void windowClosing(WindowEvent e) {          System.out.println("Window is Closing");          dispose();          System.exit(0);       }       public void windowActivated(WindowEvent e) {          System.out.println("Window Activated");       public void windowDeactivated(WindowEvent e) {          System.out.println("Window Deactivated");       public void windowDeiconified(WindowEvent e) {         System.out.println("Window Deiconified");

13. JAVA GUI [윈도우이벤트 예제 프로그램] [윈도우이벤트 예제 프로그램]       public void windowIconified(WindowEvent e) {          System.out.println("Window Iconified");   }    });  } } public class WindowTest {    public static void main(String args[]) {      Frame1 f = new Frame1("My Frame");      f.show();    f.setSize(250, 200);    } } [실행결과] C:\JAVA\NewBook\c13>java WindowTest Window Activated Window Iconified Window Deactivated Window Deiconified Window is Closing

13. JAVA GUI 13.3.10 별도의 Listener 구현 클래스 정의 - 이벤트 발생 클래스와 이벤트 처리 클래스를 별도로 정의하여 사용 - 동일한 기능을 수행하는 다음 두 예제 프로그램 비교 [예제 프로그램 1: 기존 방식] import java.awt.*; import java.awt.event.*; class ButtonPanel extends Panel             implements ActionListener {    Button yellowB,blueB;    public ButtonPanel()    {  yellowB = new Button("Yellow");       blueB = new Button("Blue");       add(yellowB); add(blueB);       yellowB.addActionListener(this);        blueB.addActionListener(this);    }

13. JAVA GUI 13.3.10 별도의 Listener 구현 클래스 정의 [예제 프로그램 1: 기존 방식] [예제 프로그램 1: 기존 방식]    public void actionPerformed(ActionEvent evt)    {  Object source = evt.getSource();       Color color = getBackground();       if (source == yellowB) color = Color.yellow;       else if (source == blueB) color = Color.blue;       setBackground(color);       repaint();  // paint with new Background    } } public class EventTest extends Frame {  public static void main(String[] args)    {  Frame fm = new EventTest();       fm.setTitle("Event Test");           fm.add(new ButtonPanel());           fm.setSize(200,200);       fm.show();  

13. JAVA GUI 13.3.10 별도의 Listener 구현 클래스 정의 o 별도의 리스너 객체를 생성하여 등록하는 방법 [예제 프로그램 2] class MyListener implements ActionListener {  Panel panel;    MyListener(Panel p) {      panel = p;    }    public void actionPerformed(ActionEvent evt)    {  Button s= (Button) evt.getSource();       Color color = panel.getBackground();       String str = s.getActionCommand();                  if (str.equals("Yellow")) color = Color.yellow;       else if (str.equals("Blue")) color = Color.blue;       panel.setBackground(color);       panel.repaint(); // paint with new Background }

13. JAVA GUI 13.3.10 별도의 Listener 구현 클래스 정의 o 별도의 리스너 객체를 생성하여 등록하는 방법 [예제 프로그램 2] class ButtonPanel extends Panel  {    Button yellowB,blueB;    public ButtonPanel()    {  yellowB = new Button("Yellow");       blueB = new Button("Blue");       add(yellowB); add(blueB);       MyListener listen = new MyListener(this); // 왜 this를 넘길까?       yellowB.addActionListener(listen); // 인자가 this가 아님       blueB.addActionListener(listen);     } } public class EventTest2 extends Frame {  public static void main(String[] args)    {  Frame fm = new EventTest2();       fm.setTitle("Event Test");       fm.add(new ButtonPanel());       fm.setSize(200,200);       fm.show();     }}

13. JAVA GUI 13.4 어댑터(Adaptor) 클래스 - 인터페이스는 구현 클래스에서 모든 메소드 재정의 요구 - 인터페이스는 구현 클래스에서 모든 메소드 재정의 요구 - 인터페이스에서 많은 메소드가 정의되면, 귀찮음 - Adaptor 클래스 사용시 필요 클래스만 재정의

13. JAVA GUI 13.4 어댑터(Adaptor) 클래스 o Adaptor 예제 프로그램 [첫 번째 예제 프로그램: Listener 인터페이스 사용] import java.awt.*; import java.awt.event.*; class ListenerTest extends Frame implements WindowListener { ListenerTest(String title) {     super(title);     addWindowListener(this);   }   public static void main(String args[]) {     ListenerTest f = new ListenerTest("Listener");     f.setSize(300,200);     f.show();   public void windowActivated(WindowEvent e) { }   public void windowClosed(WindowEvent e) { }   public void windowClosing(WindowEvent e) {        System.exit(0); // Make this program end

13. JAVA GUI 13.4 어댑터(Adaptor) 클래스 o Adaptor 예제 프로그램 [첫 번째 예제 프로그램: Listener 인터페이스 사용]   public void windowDeactivated(WindowEvent e) {}   public void windowDeiconified(WindowEvent e) {}   public void windowIconified(WindowEvent e) {}   public void windowOpened(WindowEvent e) {} }

13. JAVA GUI 13.4 어댑터(Adaptor) 클래스 o Adaptor 예제 프로그램 import java.awt.*; import java.awt.event.*; class MyAdapter extends WindowAdapter {   public void windowClosing(WindowEvent e) {     System.exit(0);   } } class AdapterTest extends Frame {   AdapterTest(String title) {     super(title);     addWindowListener(new MyAdapter());    public static void main(String args[]) {     AdapterTest f = new AdapterTest("Adapter");         f.setSize(300, 200);         f.show();