CSE 114: Computer Science I. Unit 16: Event-driven Programming and Animation. Motivation. Event Handling. Event Handling

Motivation • Suppose you wish to write a GUI program that lets the user enter a loan amount, annual interest rate, and number of years and click the C...
Author: Merry Warren
0 downloads 4 Views 345KB Size
Motivation • Suppose you wish to write a GUI program that lets the user enter a loan amount, annual interest rate, and number of years and click the Calculate button to obtain the monthly payment and total payment • You have to use event-driven programming to write the code to respond to the button-clicking event • Procedurally written programs execute programs in a linear manner that is insufficient to handle user interaction of windows-based programs

CSE 114: Computer Science I Unit 16: Event-driven Programming and Animation Kevin McDonnell

Stony Brook University – CSE 114

1

Event Handling

2

• Event-handling code can be implemented in several ways that we will explore • One way is to encapsulate an event-handling method in a new class that implements the EventHandler interface • Here we are exploiting polymorphism • To handle button presses we need to implement the method public void handle(ActionEvent e) • Then we construct an object of our new class and associate it with the button calling the setOnAction method of the button object • See HandleEvent.java (p. 587)

• The button is an event source object – where the action originates. • You need to create an object capable of handling the action event on a button. This object is called an event handler. Stony Brook University – CSE 114

Stony Brook University – CSE 114

Event Handling

• Consider a simple graphical program containing two buttons • We wish to write code that will be executed when the buttons are pressed

Kevin McDonnell

Kevin McDonnell

3

Kevin McDonnell

Stony Brook University – CSE 114

4

Event Classes

Common Event Types

• A sampling of some of the event types in JavaFX • Note the use of inheritance

Kevin McDonnell

Stony Brook University – CSE 114

User Action Click a button Press Enter in a text field Check or uncheck Check or uncheck Select a new item Mouse pressed Mouse released Mouse clicked Mouse moved Mouse dragged Key pressed Key released Key typed 5

Registering Event Handlers

Stony Brook University – CSE 114

Event Registration Method setOnAction(EventHandler)

TextField

ActionEvent

setOnAction(EventHandler)

RadioButton

ActionEvent

setOnAction(EventHandler)

CheckBox

ActionEvent

setOnAction(EventHandler)

ComboBox

ActionEvent

setOnAction(EventHandler)

Node, Scene

MouseEvent

setOnMousePressed(EventHandler) setOnMouseReleased(EventHandler) setOnMouseClicked(EventHandler) setOnMouseMoved(EventHandler) setOnMouseDragged(EventHandler)

Node, Scene

KeyEvent

setOnKeyPressed(EventHandler) setOnKeyReleased(EventHandler) setOnKeyTyped(EventHandler)

Stony Brook University – CSE 114

6

The Delegation Model

• Java uses a delegation-based model for event handling: a source object fires an event, and an object interested in the event handles it, called an event handler or event listener • For an object to be a handler for an event on a source object, two things are needed: 1. The handler object must be an instance of the corresponding event-handler interface to ensure that the handler has the correct method for processing the event 2. The handler object must be registered by the source object that might fire the event

Kevin McDonnell

Kevin McDonnell

Source Object Event Type Fired Button ActionEvent

• The general structure:

• Example for handling a button press:

7

Kevin McDonnell

Stony Brook University – CSE 114

8

Event Objects

Inner Classes • Did you notice that the EnlargeHandler and ShrinkHandler classes were actually defined inside the ControlCircle class?

• Contain information about the event, such as: • (x, y) location of the mouse when a button was clicked • event source that was interacted with (EventObject.getSource())

• These are examples of inner classes • An inner class is a class defined within the scope of another class • Such classes are often used to reduce the number of source files and avoid naming conflicts (i.e., we can actually defined two classes with the same name in the same program, but with non-overlapping scopes)

• what key on the keyboard was pressed • among others • Listeners use them to properly respond to the event • See ControlCircleWithoutEventHandling.java (p. 590) • See ControlCircle.java (p. 592)

Kevin McDonnell

Stony Brook University – CSE 114

9

Important Inner Class Properties

Stony Brook University – CSE 114

Stony Brook University – CSE 114

10

Inner Class Example public class TestInnerClass { public static void main(String[] args) { new OtherClass(); } class InnerClass { // non-static inner class public InnerClass() { System.out.println("InnerClass constructor"); } } static class StaticInnerClass { // only inner classes can be static public static void staticMethod() { System.out.println("StaticInnerClass.staticMethod"); } } } class OtherClass { public OtherClass() { System.out.println("OtherClass constructor"); TestInnerClass obj1 = new TestInnerClass(); TestInnerClass.InnerClass in1 = obj1.new InnerClass(); TestInnerClass.StaticInnerClass.staticMethod(); } }

• An inner class can reference the data and the methods defined in the outer class in which it nests • An inner class can be defined with a visibility modifier • An inner class can be defined as static . A static inner class can be accessed using the outer class name. A static inner class cannot access non-static members of the outer class. • Objects of an inner class are often created in the outer class, but they can be created from another class • For GUIs it makes sense to create inner classes inside the GUI classes themselves because the event-handling code makes sense only in the context of the GUI itself Kevin McDonnell

Kevin McDonnell

11

Kevin McDonnell

Stony Brook University – CSE 114

12

Inner Class Example

Anonymous Inner Classes

public class TestInnerClass { OUTPUT: OtherClass constructor public static void main(String[] args) { InnerClass constructor new OtherClass(); StaticInnerClass.staticMethod } class InnerClass { // non-static inner class public InnerClass() { System.out.println("InnerClass constructor"); } } static class StaticInnerClass { // only inner classes can be static public static void staticMethod() { System.out.println("StaticInnerClass.staticMethod"); } } } class OtherClass { public OtherClass() { System.out.println("OtherClass constructor"); TestInnerClass obj1 = new TestInnerClass(); TestInnerClass.InnerClass in1 = obj1.new InnerClass(); TestInnerClass.StaticInnerClass.staticMethod(); } } Kevin McDonnell

Stony Brook University – CSE 114

13

Anonymous Inner Classes

• An anonymous inner class is an inner class without a name • It combines defining an inner class and creating an instance of the class into one step • An anonymous inner class must always extend a superclass or implement an interface, but it cannot have an explicit extends or implements clause. • An anonymous inner class must implement all the abstract methods in the superclass or in the interface • An anonymous inner class always uses the no-arg constructor from its superclass to create an instance • See AnonymousHandlerDemo.java (p. 595) Kevin McDonnell

Stony Brook University – CSE 114

14

Quiz 16A: Simple Calculator • Write a program to perform addition, subtraction, multiplication and division. Use HBoxes to center the labels, text fields and buttons. Put the HBoxes in a BorderPane. Handle bad input cleanly using proper exception-handling.

Anonymous class

Named class

Kevin McDonnell

Stony Brook University – CSE 114

15

Kevin McDonnell

Stony Brook University – CSE 114

16

Basic Syntax for a Lambda Expr.

Lambda Expressions • A lambda expression is a concise way of defining an anonymous class. New in Java 8.

• The basic syntax for a lambda expression is either: (type1 param1, type2 param2, ...) -> expression or (type1 param1, type2 param2, ...) -> { statements; } • The data type for a parameter may be explicitly declared or implicitly inferred by the compiler • The parentheses can be omitted if there is only one parameter without an explicit data type • See LambdaHandlerDemo.java (p. 598) • Note the variation in how the expressions are written on lines 25, 29, 33 and 37

btEnlarge.setOnAction( new EventHandler() { @Override public void handle(ActionEvent e) { // Code for processing event e } } btEnlarge.setOnAction(e -> { }); // Code for processing event e });

Anonymous class Kevin McDonnell

Lambda expression Stony Brook University – CSE 114

17

Single Abstract Method Interface

Kevin McDonnell

Stony Brook University – CSE 114

18

Example: Loan Calculator • Note use of GridPane and lambda expressions in this example • See LoanCalculator.java (p. 600)

• For the compiler to understand lambda expressions, the interface being implemented must contain exactly one abstract method. • Otherwise, the lambda expression will not compile • For example, the EventHandler interface contains just one abstract method, namely, handle() • Such an interface is known as a functional interface, or a Single Abstract Method (SAM) interface • Lambda expressions are available in a number of other programming languages, including Python, C# and JavaScript. They can simplify code significantly when used properly. Kevin McDonnell

Stony Brook University – CSE 114

19

Kevin McDonnell

Stony Brook University – CSE 114

20

Mouse Events

Key Events

• A MouseEvent is fired whenever a mouse button is pressed, released, clicked, moved, or dragged on a node or a scene • The MouseEvent object captures the event, such as the number of clicks associated with it, the location (the x and y coordinates) of the mouse, or which mouse button was pressed • Various getter methods (e.g., getX(), isControlDown()) give the state of the mouse and some keyboard keys • See MouseEventDemo.java (p. 602)

Kevin McDonnell

Stony Brook University – CSE 114

21

• See ControlCircleWithMouseAndKey.java (p. 605)

Stony Brook University – CSE 114

Kevin McDonnell

Stony Brook University – CSE 114

22

Listeners for Observable Objects

Example: Mouse and Key Control

Kevin McDonnell

• A KeyEvent is fired whenever a key is pressed, released, or typed on a node or a scene. Only a focused node can receive a KeyEvent. • Focus can be taken via the requestFocus() method • The KeyEvent object describes the nature of the event (namely, that a key has been pressed, released, or typed) and the value of the key • Every key event has an associated code that is returned by the getCode() method • The key codes are constants defined in the KeyCode enum and include letters, numbers, and the various keys that are not associated with printable characters (e.g., Control) • See KeyEventDemo.java (p. 604)

• You can add a listener to process a value change in an observable object (an instance of Observable) • Every binding property is an instance of Observable • Observable contains the addListener(InvalidationListener listener) method for adding a listener • The listener class must implement the InvalidationListener interface to override the invalidated(Observable o) method for handling the value change • See ObservablePropertyDemo.java (p. 607) • See DisplayResizableClock.java (p. 607) 23

Kevin McDonnell

Stony Brook University – CSE 114

24

Animation in JavaFX

Animation in JavaFX

• JavaFX provides the Animation class with the core functionality for all animations, including methods to pause, play and stop the animation • The PathAnimation class animates the moves of a node along a path from one end to the other over a given time • See FlagRisingAnimation.java (p. 611) • See PathTransitionDemo.java (p. 610) • The FadeTransition class animates the change of the opacity in a node over a given time • See FadeTransitionDemo.java (p. 612)

Kevin McDonnell

Stony Brook University – CSE 114

• Whereas PathTransition and FadeTransition define specialized animations, the Timeline class can be used to program any animation using one or more KeyFrame objects • A KeyFrame is constructed using new KeyFrame(Duration duration, EventHandler onFinished) • A Timeline is constructed using new Timeline(KeyFrame... keyframes) • See TimelineDemo.java (p. 614) • See ClockAnimation.java (p. 615)

25

JavaFX on Devices

26

• Write a program that calculates the future value of an investment at a given interest rate for a specified number of years. Use a GridPane to lay out the UI elements. The formula for the calculation is:

• See http://docs.oracle.com/javase/8/javafx/eventstutorial/gestureeventsjava.htm and http://docs.oracle.com/javase/8/javafx/eventstutorial/toucheventsjava.htm

Stony Brook University – CSE 114

Stony Brook University – CSE 114

Quiz 16B: Financial Calculator

• JavaFX has event programming support for mobile devices: javafx.scene.input.SwipeEvent javafx.scene.input.TouchEvent javafx.scene.input.ZoomEvent

Kevin McDonnell

Kevin McDonnell

futureValue = investmentAmount * (1 + monthlyInterestRate)years*12

27

Kevin McDonnell

Stony Brook University – CSE 114

28

Suggest Documents