95-712 OOP Java1 Event Handling Overview Listeners, Adapters and Event Sources Inner classes Event Handling Details Applets and GUI Applications Event.

Slides:



Advertisements
Similar presentations
Summer A-2000, Project Course-- Carnegie Mellon University 1 Financial Engineering Project Course.
Advertisements

Event Handling. In this class we will cover: Basics of event handling The AWT event hierarchy Semantic and low-level events in the AWT.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 14 Event-Driven Programming.
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.
For IST410 Students only Events-1 Event Handling.
Event-Driven Programming
Carnegie Mellon University, Graduate School of Industrial Administration 1 Event Handling Inner classes Event Handling and Inner Classes GUI Programming.
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.
Java 212: Interfaces Intro to UML Diagrams. UML Class Diagram: class Rectangle +/- refers to visibility Color coding is not part of the UML diagram.
Intermediate Java1 An example that uses inner classes Week Four Continued.
1 lecture 12Lecture 13 Event Handling (cont.) Overview  Handling Window Events.  Event Adapters Revisited.  Introduction to Components and Containers.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 16 Event-Driven Programming.
GUI Event Handling Nithya Raman. What is an Event? GUI components communicate with the rest of the applications through events. The source of an event.
3461 Sequential vs. Event-driven Programming Reacting to the user.
Mouse Events. Handling Mouse Events Java provides two listener interfaces to handle mouse events: MouseListener;  MouseListener;  MouseMotionListener.
ACM/JETT Workshop - August 4-5, ExceptionHandling and User Interfaces (Event Delegation, Inner classes) using Swing.
More Event Handling Adapters Anonymous Listeners Pop menus Validating User Input.
CS 11 java track: lecture 4 This week: arrays interfaces listener classes inner classes GUI callbacks.
Java GUI’s are event driven, meaning they generate events when the user interacts with the program. Typical events are moving the mouse, clicking a mouse.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 14 Event-Driven Programming.
(c) University of Washington07b-1 CSC 143 Java Events, Event Handlers, and Threads Reading: Ch. 17.
CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
COMP 321 Week 2. Outline Event-Driven Programming Events, Event Sources, Event Listeners Button and Timer Events Mouse Events, Adapters.
Pravin Yannawar, DOCS, NMU Jalgaon. Basic Java : Event handling in AWT and Swing 2 Objectives of This Session Explain the Event handling mechanism & demonstrate.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
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.
Anonymous Classes An anonymous class is a local class that does not have a name. An anonymous class allows an object to be created using an expression.
Lesson 6 Programming Techniques Event Handling /EvH/ AUBG ICoSCIS Team Assoc. Prof. Stoyan Bonev March, , 2013 SWU, Blagoevgrad.
Object Oriented Programming.  Interface  Event Handling.
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.
Ch13 Creating windows and applets. Short overview AWT (Abstract Windowing Toolkit) Early Java development used graphic classesEarly Java development used.
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 10: Event Handling 1 Event Handling.
GUI DYNAMICS Lecture 11 CS2110 – Fall GUI Statics and GUI Dynamics  Statics: what’s drawn on the screen  Components buttons, labels, lists, sliders,
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 10: Event Handling 1 Chapter 10 Event Handling.
Java the UML Way versjon Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
Event-Driven Programming CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
1 Event Handling – Lecture 4 Prepared by: Ahmad Ramin Rahimee Assistant Professor ICTI.
1/18H212Mouse and Timer Events H212 Introduction to Software Systems Honors Lecture #16: Mouse and Timer Events October 26, 2015.
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.
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.
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
Lesson 28: More on the GUI button, frame and actions.
Object Oriented Programming in Java Habib Rostami Lecture 10.
UQC117S2 Graphics Programming Lecture 2 Event Handling Program as a sequence of instructions Event -driven program Need to detect the event and carry out.
Sep 181 Example Program DemoTranslateEnglishGUI.java.
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.
1 DemoBasic_v3, DemoBasic_v4 JButton JLabel. 2 Registering an ActionListener Register by invoking the following from within constructor DemoBasicFrame.
Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit7: Event-driven programming 1.
CSC 205 Programming II Lecture 5 AWT - I.
Events and Event Handling
Chapter 14 Event-Driven Programming
CompSci 230 S Programming Techniques
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.
Event Handling Chapter 2 Objectives
GUI III IS
Programming in Java Event Handling
GUI Event Handling Nithya Raman.
Event-driven programming for GUI
Introduction to Computing Using Java
Chapter 16 Event-Driven Programming
Events, Event Handlers, and Threads
Programming Graphical User Interface (GUI)
Presentation transcript:

OOP Java1 Event Handling Overview Listeners, Adapters and Event Sources Inner classes Event Handling Details Applets and GUI Applications Event Handling

OOP Java2 Event Handling Used by the Abstract Window Toolkit (AWT) – for basic GUI programming Java 1.0 Used by Swing -- Better components than AWT Java 2 Used by JavaBeans -- reusable software components, like Visual Basic, that can be manipulated in a builder tool

OOP Java3 Babysitting A baby in the home needs attention. Many events surrounding the baby are not easily ignored. Events can be of different types.

OOP Java4 One possible source of events

OOP Java5 Babysitting Before responding to an event, a babysitter typically takes note of the source and the type of event.

OOP Java6 Babysitting The sitter needs to know both the event type and the event source. Event source Event type Handler

OOP Java7 Event Handling The window manager software may generate hundreds of different events. Examples include mouse clicks, mouse movements, key strokes, and timer ticks. A programmer is typically interested in a small subset of all of the possible events that may occur.

OOP Java8 Events and Event Objects Since events may be of different types but still exhibit some shared traits (inheritance) Java represents the event classes in a hierarchy. The root class is called java.util.EventObject. The only common feature shared by all events is a source object. So we find the following method in the EventObject class : public Object getSource();

OOP Java9 EventObject AWTEvent ActionEventComponentEvent InputEvent WindowEvent MouseEvent KeyEvent Some classes and methods in the event hierarchy. Object String getActionCommand() int getX() char getKeyChar() boolean isAltDown()Window getWindow()

OOP Java10 Event handling usually involves three types of objects Objects are used to hold and report on information about the event. Objects are typically the source of events. Objects, called listeners, are used to handle events.

OOP Java11 Example A mouse object A mouse object An event object that describes, say, the x and y coordinate of where the mouse was clicked The listener object has methods that are called for particular events Event Source Event data and methods Listener

OOP Java12 Example A mouse object A mouse object An event object that describes, say, the x and y coordinate of where the mouse was clicked The listener object has methods that are called for particular events Implements MouseListener The event object is sent to a listener method A mouse object must be told who its listener is.

OOP Java13 The Listener There are different types of Listeners. MouseListeners WindowListeners ScrollBarListeners Etc.. These Listeners are interfaces. Remember what an interface provides? If class X implements an interface then class X promises to provide (at least) the methods declared in the interface.

OOP Java14 Some of the Listener Hierarchy EventListener ActionListener abstract void actionPerformed(ActionEvent e); MouseListener abstract void mouseClicked(MouseEvent e) KeyListener

OOP Java15 A Listener Interface public interface MouseListener { void mouseClicked(MouseEvent e); void mouseEntered(MouseEvent e); void mouseExited(MouseEvent e); void mouseReleased(MouseEvent e); } //What does it mean if I claim that I implement this interface?

OOP Java16 An Example // MouseSpyApplet.java import java.applet.Applet; import java.awt.event.MouseEvent; import java.awt.event.MouseListener;

OOP Java17 class MouseSpy implements MouseListener { public void mouseClicked(MouseEvent event) { System.out.println("Mouse clicked. x = " + event.getX() + " y = " + event.getY()); } public void mouseEntered(MouseEvent event) { System.out.println("Mouse entered. x = " + event.getX() + " y = " + event.getY()); } public void mouseExited(MouseEvent event) { System.out.println("Mouse exited. x = " + event.getX() + " y = " + event.getY()); } public void mousePressed(MouseEvent event) { System.out.println("Mouse pressed. x = " + event.getX() + " y = " + event.getY()); } public void mouseReleased(MouseEvent event) { System.out.println("Mouse released. x = " + event.getX() + " y = " + event.getY()); } I have to provide ALL of these methods!!

OOP Java18 public class MouseSpyApplet extends Applet { public MouseSpyApplet() { MouseSpy listener = new MouseSpy(); addMouseListener(listener); }

OOP Java19 Spying on the mouse Java Applets need an HTML file.

OOP Java20 Another approach Suppose a friendly sole created this class: public class MouseAdapter implements MouseListener { void mouseClicked(MouseEvent e){} void mouseEntered(MouseEvent e){} void mouseExited(MouseEvent e){} void mousePressed(MouseEvent event) {} void mouseReleased(MouseEvent e){} } Now, suppose I extend this class. What must I provide?

OOP Java21 Only those methods that I am interested in. The other methods, when called, do nothing. We’ll visit this issue again later.

OOP Java22 Inner Classes Nested Top Level Classes (not inner) Member Classes Local Classes Anonymous Classes

OOP Java23 Nested Top Level Class Nested top-level classes are not inner classes. Use as a convenient way to group related classes Since the class must be static and has no 'this' pointer, it has no access to the instance data of objects for its enclosing class. It behaves just like a 'normal' class or interface.

OOP Java24 //NestedTopLevelExample.java class Top { int i,j; static class SomeClass { // static makes it top-level nested int k; SomeClass() { System.out.println("Constructing SomeClass"); } void foo() { System.out.println("Hello"); } } Top() { System.out.println("Constructing a Top object"); }

OOP Java25 public class NestedTopLevelExample { public static void main(String args[]) { Top myTop = new Top(); Top.SomeClass myObject = new Top.SomeClass(); myObject.foo(); } Output Constructing a Top object Constructing SomeClass Hello

OOP Java26 Member Classes (1) Member classes (there is no such thing as a 'member‘ interface) This inner class (it's not a top-level class) has no static keyword and can access the members of each object of its outer class. The class 'appears in every instance'.

OOP Java27 The parent class must declare an instance of an inner class, before it can invoke the inner class methods, assign to data fields (including private ones), and so on. Unlike nested top-level classes, inner classes are not directly part of a package and are not visible outside the class in which they are nested. Inner classes are often used for GUI event handlers. Member Classes (2)

OOP Java28 // MemberClassExample.java class Top { int i = 33; public class SomeClass { // access the outer object's state. private int k = i; SomeClass() { System.out.println("Constructing SomeClass"); } void foo() { System.out.println("Hello"); } } Top() { System.out.println("Constructing a Top object"); SomeClass sc = new SomeClass(); System.out.println(sc.k); }

OOP Java29 public class MemberClassExample { public static void main(String args[]) { Top myObject = new Top(); } // OUTPUT Constructing a Top object Constructing SomeClass 33

OOP Java30 Local Classes A local class is an inner class. Typically, a local class is declared within a method. It is not a member of an enclosing class. It is visible only within a block. These classes are used primarily as "adapter classes". For example, a block of code that creates a Button object could use a local class to define a simple implementation of the ActionListener Interface. Then it could instantiate this simple implementation and pass the resulting object to the button's ActionListener method, thereby connecting the button to the "callback" code that is executed when the button is pressed.

OOP Java31 // Local Class example class Top { int i = 33; Top() { System.out.println("Constructing a Top object"); // define a class within a method class Wow { int t; Wow() { System.out.println("Building a Wow"); i = 8; t = 9; } Wow h = new Wow(); System.out.println(" h.t == " + h.t); System.out.println(" i == " + i); }

OOP Java32 public class LocalExample { public static void main(String args[]) { Top myObject = new Top(); } // OUTPUT Constructing a Top object Building a Wow h.t == 9 i == 8

OOP Java33 An anonymous class is refinement of inner classes. It allows you to combine the definition of the class with the instance allocation. Since it is instantiated in the same expression that defines it, it can only be instantiated once. This is very similar to local classes. When writing a simple adapter class, the choice between a named local class and an unnamed anonymous class typically comes down to a matter of style and code clarity, rather than any difference in functionality. The new class can't have a constructor. Anonymous Classes

OOP Java34 // Anonymous.java interface SmallClass { public void foo(); } class Top { int i = 33; void someMethod(SmallClass s) { s.foo(); } void anotherMethod() { someMethod(new SmallClass() { public void foo() { System.out.println("Really fun"); } }); }

OOP Java35 Top() { System.out.println("Constructing a Top object"); someMethod(new SmallClass() { public void foo() { System.out.println("Strange but fun"); } }); }

OOP Java36 public class Anonymous { public static void main(String args[]) { // We can't create interface objects // error: SmallClass s = new SmallClass(); Top myObject = new Top(); myObject.anotherMethod(); } // OUTPUT Constructing a Top object Strange but fun Really fun

OOP Java37 Event Handling – Details register Source ObjectListener Object fire events After the listener object registers itself with the source object, the source object calls a method found in the listener object and passes an object that describes the event. Event object

OOP Java38 Event Handling Suppose we have a Button object Button b = new Button(); We must determine what events a particular component generates. A Button component may generate an ActionEvent object. Button b ActionEvent Object ActionEvent Object

OOP Java39 Implementing a Listener class BabySitter implements ActionListener { public void actionPerformed(ActionEvent e) { // handle the event object e in some way } We need an object that will listen for the ActionEvent. We implement the ActionListener class (this class listens for ActionEvents from buttons, menus, etc.) and override its actionPerformed method.

OOP Java40 Create a BabySitter object BabySitter sitter = new BabySitter(); sitter

OOP Java41 Registering The Listener We want to listen for the ActionEvent object coming from the button. So, we tell the button what object will listen for the ActionEvent object: b.addActionListener(sitter)

OOP Java42 The button and its listener Button Object Sitter Object The button calls the actionPerformed() method of the sitter object and passes an ActionEvent object as a parameter addActionListener

OOP Java43 Hit the X and the program exits Once again but with a window

OOP Java44 Create a WindowCloseSitter Class import javax.swing.*; import java.awt.event.*; public class CloseDemo { public static void main(String[] args) { JFrame f = new JFrame("Example"); f.setSize(400,100); f.setVisible(true); WindowCloseSitter h = new WindowCloseSitter(); f.addWindowListener(h); }

OOP Java45 class WindowCloseSitter implements WindowListener { public void windowClosing(WindowEvent e) { System.exit(0); } public void windowClosed(WindowEvent e) { } public void windowOpened(WindowEvent e) { } public void windowIconified(WindowEvent e) { } public void windowDeiconified(WindowEvent e) { } public void windowActivated(WindowEvent e) { } public void windowDeactivated(WindowEvent e) { } } But we have to implement ALL of the functions !!

OOP Java46 Java Provides Adapter Classes ComponentAdapter MouseMotionAdapter WidowAdapter ContainerAdapter MouseAdapter FocusAdapter KeyAdapter

OOP Java47 The WindowAdapter class public abstract class WindowAdapter implements WindowListener { public void windowClosing(WindowEvent e) {} public void windowClosed(WindowEvent e) { } public void windowOpened(WindowEvent e) { } public void windowIconified(WindowEvent e) { } public void windowDeiconified(WindowEvent e) { } public void windowActivated(WindowEvent e) { } public void windowDeactivated(WindowEvent e) { } } A built in class -- we already have the empty bodies!!

OOP Java48 The Window again import javax.swing.*; import java.awt.event.*; public class CloseDemo2 extends WindowAdapter { public static void main(String[] args) { JFrame f = new JFrame("Example"); f.setSize(400,100); f.setVisible(true); f.addWindowListener(new CloseDemo2()); } public void windowClosing(WindowEvent e) { System.exit(0); }

OOP Java49 Again with anonymous classes import javax.swing.*; import java.awt.event.*; public class CloseDemo3 { public static void main(String[] args) { JFrame f = new JFrame("Example"); f.setSize(400,100); f.setVisible(true); f.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } ); } }