Event-Driven Programming - Computer Science

Transcription

Event-Driven ProgrammingIntroduction to Programming andComputational Problem Solving - 2CSE 8BLecture 17

Announcements Assignment 8 is due Dec 9, 11:59 PM Quiz 8 is Dec 11 Educational research study– Dec 11, weekly reflection– Dec 18, post-class survey Final exam is Dec 17 Course and Professor Evaluations (CAPE)– https://cape.ucsd.edu/– Must by completed before Dec 14, 8:00 AM Reading– Chapter 15CSE 8B, Fall 20202

Event-driven programming An event is an object created from an eventsource You can write code to process events such as abutton click, mouse movement, andkeystrokesCSE 8B, Fall 20203

Procedural programming vs.event-driven programming Procedural programming– Code is executed in procedural order Event-driven programming– Code is executed upon activation of eventsCSE 8B, Fall 20204

Event-related objects Event source object– Where the action originates Event object– Created from an event source Event handler object– Processes the eventEvent source objectEvent objectCSE 8B, Fall 2020Event handler object5

Event sources An event source is an object that can create anevent– An event can be defined as a type of signal to theprogram that some external action has happened For example– Button is event source– Button click action isthe event it createsCSE 8B, Fall 20206

Events An event is an object created from an eventsource An event object contains whatever propertiesare pertinent to the eventCSE 8B, Fall 20207

Events You can identify the source object of the event usingthe getSource() instance method in the EventObjectclass The subclasses of EventObject deal with special typesof eventsCSE 8B, Fall 20208

Mouse events A MouseEvent is fired whenever a mouse buttonis pressed, released, clicked, moved, or draggedCSE 8B, Fall 20209

Key events A KeyEvent is fired whenever a key ispressed, released, or typedCSE 8B, Fall 202010

KeyCode constants Every key event has an associated code returnedby the getCode() method in KeyEventCSE 8B, Fall 202011

Event handlers Not all objects can handle events An object capable of handling an event iscalled an event handler– The event handler processes the event An event handler must be an instance of anappropriate event-handling interface An event handler must be registered with anevent source objectCSE 8B, Fall 202012

Event handlers The event handler must be an instance of theEventHandler T extends Event interface– T extends Event denotes that T is a generictype that is a subtype of Event– This interface defines the common behavior for allhandlers The EventHandler ActionEvent interfacecontains the handle(ActionEvent) methodfor processing the action event– An event handler class must override this method torespond to the eventCSE 8B, Fall 202013

Event handlers The EventHandler object handler must beregistered with the event source objectsource using the methodsource.setOnAction(handler) Firing an event means to create an event anddelegate the handler to handle the eventCSE 8B, Fall 202014

Event handlers The EventHandler ActionEvent interface contains thehandle(ActionEvent) method forprocessing the action event An event handler class must override thismethod to respond to the eventCSE 8B, Fall 202015

Examplepublic class HandleEvent extends Application {@Override // Override the start method in the Application classpublic void start(Stage primaryStage) {// Create a pane and set its properties.Create event sourceButton btOK new Button("OK");OKHandlerClass handler1 new OKHandlerClass();btOK.setOnAction(handler1);Create event handlerRegister event handler.}}Event handler classclass OKHandlerClass implements EventHandler ActionEvent {@Overridepublic void handle(ActionEvent e) {Handle eventSystem.out.println("OK button clicked");}CSE 8B, Fall 2020}16

Examplepublic class HandleEvent extends Application {@Override // Override the start method in the Application classpublic void start(Stage primaryStage) {// Create a pane and set its properties.Button btOK new Button("OK");OKHandlerClass handler1 new OKHandlerClass();btOK.setOnAction(handler1);1. Click OK.}}class OKHandlerClass implements EventHandler ActionEvent {@Overridepublic void handle(ActionEvent e) {System.out.println("OK button clicked");}CSE 8B, Fall 2020}17

Examplepublic class HandleEvent extends Application {@Override // Override the start method in the Application classpublic void start(Stage primaryStage) {// Create a pane and set its properties.2. The JVMinvokes thehandler class’s handle methodButton btOK new Button("OK");OKHandlerClass handler1 new ss OKHandlerClass implements EventHandler ActionEvent {@Overridepublic void handle(ActionEvent e) {System.out.println("OK button clicked");}CSE 8B, Fall 2020}18

ExampleCSE 8B, Fall 202019

Common user actions, source objects,and event types generatedCSE 8B, Fall 202020

Inner classes An event handler class designed specifically tocreate an event handler object for a graphicaluser interface (GUI) component (e.g., abutton) is not be shared by other applications– As such, it is appropriate to define the eventhandler class inside the class that uses itCSE 8B, Fall 202021

Inner classes An inner class (or nested class) is a classdefined within the scope of another class An inner class can reference the data andmethods defined in the outer class in which itnests, so you do not need to pass thereference of the outer class to the constructorof the inner classCSE 8B, Fall 202022

Inner classesCSE 8B, Fall 202023

Inner classes An inner class can be declared public,protected, or private subject to the samevisibility rules applied to a member of theclass An inner class can be declared static– A static inner class can be accessed using theouter class name– A static inner class cannot access nonstaticmembers of the outer classCSE 8B, Fall 202024

Inner classes Normally, you only define an inner class if it isonly used by its outer class Outside the outer class, an inner class may beused just like a regular class– Create an instance of an inner class using: If the inner class is nonstaticOuterClass.InnerClass innerObject outerObject.new InnerClass(); If the inner class is staticOuterClass.InnerClass innerObject new OuterClass.InnerClass()CSE 8B, Fall 202025

Inner classes Inner classes can make programs simple andconcise An inner class supports the work of itscontaining outer class An inner class does not need its own sourcefile and is compiled into a class namedOuterClassName InnerClassName.class Inner classes also avoid class-naming conflictsCSE 8B, Fall 202026

Anonymous inner classes An anonymous inner class is an inner classwithout a name It combines defining an inner class andcreating an instance of the class into one stepCSE 8B, Fall 202027

Anonymous inner classes An anonymous inner class must always extend asuperclass or implement an interface, but it cannothave an explicit extends or implements clause An anonymous inner class must implement all theabstract methods in the superclass or in the interface An anonymous inner class always uses the no-argconstructor from its superclass to create an instance– If an anonymous inner class implements an interface, thenthe constructor is Object() An anonymous inner class is compiled into a classnamed OuterClassName n.class, where n 1, .CSE 8B, Fall 202028

Lambda expressions Lambda expressions can be viewed as ananonymous method with a concise syntax The basic syntax for a lambda expression is either(type1 param1, type2 param2, .) - expression orNo semicolon(type1 param1, type2 param2, .) - { statements; } The data type for a parameter may be explicitlydeclared or implicitly inferred by the compiler The parentheses can be omitted if there is onlyone parameter without an explicit data typeCSE 8B, Fall 202029

Lambda expressions The compiler treats a lambda expression as ifit is an object created from an anonymousinner class– The compiler processes a lambda expression inthe following three steps1. Identify the lambda expression type2. Identify the parameter types3. Identify statementsCSE 8B, Fall 202030

Lambda expressions Lambda expressions can be used to greatlysimplify code for event handling– For example(ActionEvent e) - { circlePane.enlarge(); }(e) - { circlePane.enlarge(); }All four of thesee - { circlePane.enlarge(); }are equivalente - circlePane.enlarge()btEnlarge.setOnAction(new EventHandler ActionEvent () {@Overridepublic void handle(ActionEvent e) {// Code for processing event e}}});(a) Anonymous inner class event handler CSE 8B, Fall 2020btEnlarge.setOnAction(e - {// Code for processing event e});(b) Lambda expression event handler31

Lambda expressions ExamplebtEnlarge.setOnAction(e - {// Process event e});1. The compiler recognizes the lambdaexpression type is an object of theEventHandler ActionEvent type,because the expression is an argumentin the setOnAction method2. The compiler recognizes e is a parametertype of the ActionEvent type, because theEventHandler ActionEvent interfacedefines the handle method with aparameter of the ActionEvent typeCSE 8B, Fall 20203. The compiler recognizes the codefor processing event e are thestatements in the handle methodbtEnlarge.setOnAction(new EventHandler ActionEvent () {@Overridepublic void handle(ActionEvent e) {// Code for processing event e}}32});btE/});

Lambda expressions The statements in the lambda expression is all for thatmethod If it contains multiple methods, the compiler will notbe able to compile the lambda expression As such, for the compiler to understand lambdaexpressions, the interface must contain exactly oneabstract method– Such an interface is known as a single abstract method(SAM) interface Essentially, a lambda expression creates an object,and the object performs a function by invoking thissingle methodCSE 8B, Fall 202033

Single abstraction method (SAM) interface A SAM interface is also known as a functionalinterface An instance of a functional interface is knownas a functional object Since a lambda expression defines exactly onefunction, a lambda expression is also called alambda functionCSE 8B, Fall 202034

Listeners for observable objects You can add a listener to process a value change in anobservable object An instance of Observable is known as an observableobject, which contains theaddListener(InvalidationListener listener)method for adding a listener The listener class must implement the functional interfaceInvalidationListener to override theinvalidated(Observable o) method for handling thevalue change– Once the value is changed in the Observable object, thelistener is notified by invoking itsinvalidated(Observable o) method– Every binding property is an instance of ObservableCSE 8B, Fall 202035

Next Lecture Binary I/O Reading– Chapter 17CSE 8B, Fall 202036

Event-driven programming An event is an object created from an event source You can write code to process events such as a button click, mouse movement, and keystrokes . EventHandler T extends Event interface – T extends Event denotes that Tis a generic type that is a subtype of