Java Fx

Post on 01-Sep-2014

6.441 views 3 download

Tags:

description

Presentation on Java FX

Transcript of Java Fx

11

JavaFX Workshop

What is & Why JavaFX?What is & Why JavaFX?

Rich Clients Are Changing the Game!• Clients are becoming visually rich> Too much engineering effort to create using traditional tools> Challenging the conventional notion of GUI toolkits

> Buttons with image → Image buttons (HTML) → ???

• Clients are omnipresence> The concept of one software on one computer is dying...> Browsers are no longer the only client - They are used as

delivery vehicles• Clients are designed rather than programmed> Working together with graphic designers to conceptualize the

interface and use cases

JavaFX Vision

JavaFX is THE platform for creating and delivering Rich Internet Applications (RIA) across all the screens of your life

JavaFX is Powered by Java

Key Features ofKey Features ofJavaFXJavaFX

Key Features• One-stop shop RIA platform for all screens: > Build engaging visual experiences across desktop, browser

and mobile with a unified development and deployment model.

• Broadest market reach: > Distribute RIAs easily across billions of devices with the

power of Java.• Designer-developer workflow: > Dramatically shorten your production cycle for design and

development.

Key Features (Continued)• Break free from the browser: > Drag-and drop a JavaFX application from the browser to

deploy to the desktop.• Built over powerful Java runtime: > Leverage the extreme ubiquity, power, performance and

security of the Java runtime.• Java technology compatibility: > Preserve your investment by enabling the use of any Java

library within a JavaFX application.

Things You Can BuildThings You Can Buildwith JavaFXwith JavaFX

3-D Display Shelf With the PerspectiveTransform• The PerspectiveTransform built into JavaFX can be

used to easily create 3-D effects

Flying Saucer• The new out-of-process Java applet plugin in Java SE 6

update 10 enables you to make applets which can run outside of the browser.

Simple Video Player• Incorporating video in your application is as simple as

creating an instance of this component, setting a few variables and including a link to your video source.

VideoCube • Shows how to use JavaFX technology to rotate a cube

that displays video on its faces. The sample enables the user to click a cube face to play video, or drag a face to rotate the cube

JavaFX PlatformJavaFX PlatformArchitectureArchitecture

JavaFX Platform Architecture

Example: Hello World in JavaFXDeclarative SyntaxStage { title: "Welcome to JavaFX!" scene: Scene { content: [ Text { content: "Hello World!" x:25 y:25 fill: Color.BLACK font: Font{ size: 32 } } ] }}

Data TypesData Types

Basic Data Types• Boolean• Integer• Number• String• Duration

Data types cannot be null

String: Declaration• A String can be declared using either single or double

quotes: > var s1 = 'Hello';> var s2 = "Hello";

• Single and double quotes are symmetrical: you can embed single quotes within double quotes, and double quotes within single quotes.

• There is no difference between single- and double-quoted strings.

String: Embedded Expressions• You can also embed expressions inside a string using

curly braces "{}": > def name = 'Joe';> var s = "Hello {name}"; // s = 'Hello Joe'

• The embedded expression can itself contain quoted strings, which, in turn, can contain further embedded expressions: > def answer = true;> var s = "The answer is {if (answer) "Yes" else "No"}"; // s =

'The answer is Yes'

String: Joining (Concatenating)• To join (concatenate) multiple strings, use curly braces

inside the quotes:def one = "This example ";def two = "joins two strings.";def three = "{one}{two}"; // join string one and string twoprintln(three); // 'This example joins two strings.'

Number and Integer: Declaration• The Number and Integer types represent numerical data,

although for most scripting tasks, you will usually just let the compiler infer the correct type: def numOne = 1.0; // compiler will infer Number def numTwo = 1; // compiler will infer Integer• You can, however, explicitly declare a variable's type:

def numOne : Number = 1.0;def numTwo : Integer = 1;• Number represents floating-point numbers while Integer only

represents integers. • Use Number only when you absolutely need floating-point

precision. In all other cases, Integer should be your first choice.

Boolean• The Boolean type represents two values: true or false

var isAsleep = true; • or when evaluating a conditional expression:

if (isAsleep) { wakeUp();}

Duration• The Duration type represents a fixed unit of time

(millisecond, second, minute, or hour.) 5ms; // 5 milliseconds10s; // 10 seconds30m; // 30 minutes1h; // 1 hour• Durations are notated with time literals — for example,

5m is a time literal representing five minutes. • Time literals are most often used in animation

Void• Void is used to indicate that a function does not return

any value: • The following two are equivalent

// Return type is set to Voidfunction printMe() : Void { println("I don't return anything!");}// No return typefunction printMe() { println("I don't return anything!");}

Null• Null is a special value used to indicate a missing

normal value.• Null is not the same as zero or an empty string, so

comparing for null is not the same as comparing for zero or an empty string. function checkArg(arg1: Address) { if(arg1 == null) { println("I received a null argument."); } else { println("The argument has a value."); }}

Script VariablesScript Variables

Script Variables• Script variables are declared using the var or def

keywords. > The difference between the two is that var variables may be

assigned new values throughout the life of the script, whereas def variables remain constant at their first assigned value.

def numOne = 100;def numTwo = 2;var result;

Type Inference (by Compiler)

• You don't have to explicitly specify the types of variable in JavaFX

• The compiler is smart enough to figure out your intent based on the context in which the variable is used. This is known as type inference.

• Type inference makes your job as a script programmer a little easier because it frees you from the burden of declaring the data types that your variable is compatible with.

Writing Your OwnWriting Your OwnClassesClasses

Class Definition

• Address class definition: The Address class declares street, city, state, and zip instance variables all of type Stringclass Address { var street: String; var city: String; var state: String; var zip: String;}

Class Definition• Customer class definition with functions - functions are

like methods in Javaclass Customer { var firstName: String; var lastName: String; var phoneNum: String; var address: Address;

function printName() { println("Name: {firstName} {lastName}"); }

function printPhoneNum(){ println("Phone: {phoneNum}"); }}

Object LiteralsObject Literals

What is an Object? (Same as in Java)• Objects represent state and behavior> An object's state is represented by its variables.> An object's behavior is represented by its functions.

• Conceptually an object can model just about anything, from GUI components (buttons, check boxes, text labels) to non-visual abstractions (temperature data, financial records, product registration information, etc.)

Object Literal • In the JavaFX Script programming language, an object

can be created with an object literal (unlike Java)• Concise declarative syntax• Similar to JavaScript• Combine with binding for maximum benefit

Example: Object Literal

• The first word (Rectangle) specifies the type of object, class, that you are creating> variable: initial-value // initial-value is an expression

// Create a Rectangle// x: 10 is not an assignment, it is an initializationRectangle { x: 10 y: 10 width: 100 height: 100}

Declaring Object Literals• When declaring an object literal, the instance variables

may be separated by commas or whitespace, as well as the semi-colonAddress { street: "1 Main Street"; // separated by semi colon city: "Santa Clara"; // separated by semi colon}Address { street: "1 Main Street" // separated by whitespace city: "Santa Clara" // separated by whitespace}Address { street: "200 Pine Street", // separated by comma city: "San Francisco", // separated by comma}

Nesting an Object inside Another Object

• Nesting Color object inside Rectangle object

var rect = Rectangle { x: 10 y: 10 width: 100 height: 100 fill: Color { red: 1 green: 0 blue: 0 }}

Assigning an Object Literal to a Variable

// A variation that allows me to reference the// color later var color:Color;var rect = Rectangle { x: 10 y: 10 width: 100 height: 100 fill: color = Color { red: 1 green: 0 blue: 0 }}var rect2 = Rectangle { x: 200 y: 10 width: 100 height: 100 fill: color}

SequencesSequences

What is a Sequence?• In addition to the five basic data types, the JavaFX

Script programming language also provides data structures known as sequences.

• A Sequence represents an ordered list of objects; the objects of a sequence are called items.

Creating Sequences• One way to create a sequence is to explicitly list its

items. • Each element is separated by a comma and the list is

enclosed in square brackets [ and ]> For example, the following code declares a sequence and

assigns it to a variable named weekDays> var weekDays = ["Mon","Tue","Wed","Thu","Fri"];

> The compiler knows that we intend to create a "sequence of strings" because the individual items are all declared as String literals

Specifying Sequence's Type Explicitly• You can also explicitly specify a sequence's type by

modifying its variable declaration to include the name of the type followed by "[]": > var weekDays: String[] = ["Mon","Tue","Wed","Thu","Fri"];> This tells the compiler that the weekDays variable will hold a

sequence of Strings (as opposed to a single String).

Sequences Within Other Sequences• Sequences can also be declared within other

sequences: var days = [weekDays, ["Sat","Sun"]];

// In such cases, the compiler will automatically flatten the// nested sequences to form a single sequence, making the // above equivalent to: var days = ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"];

Sequences with Shorthand Notation• There is also a shorthand notation that makes it easier

to create sequences that form an arithmetic series. • To create a sequence consisting of the numbers 1

through 100, use the following: > var nums = [1..100];

Creating Sequences with Predicate

• You can use a boolean expression, or a predicate, to declare a new sequence that is a subset of an existing sequence. For example, consider the following: var nums = [1,2,3,4,5];• To create a second sequence (based on items found in this

first sequence) but containing only numbers greater than 2, use the following code: var numsGreaterThanTwo = nums[n | n > 2];// Select all items from the num sequence where the value of an// item is greater than 2 and assign those items to a new sequence// called numsGreaterThanTwo.

Accessing Sequence Items• Sequence items are accessed by numerical index, starting

at 0. • To access an individual element, type the sequence name,

followed by the element's numerical index enclosed within square brackets: var days = ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"];

println(days[0]); // prints Monprintln(days[1]); // prints Tueprintln(days[2]);println(days[3]);println(days[4]);println(days[5]);println(days[6]);

Size of a Sequence• You can determine the size of a sequence using the

sizeof operator followed by the name of the sequence> sizeof days

• The following code prints "7" to the screen: > var days = ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"];> println(sizeof days);

Inserting Items to a Sequence• The insert keyword allows you to insert an element into

a sequence, before a specific element, or after a specific element. var days = ["Mon"];// The sequence contains: "Mon" at this pointinsert "Tue" into days;insert "Fri" into days;insert "Sat" into days;insert "Sun" into days;// The sequence contains: "Mon", "Tue", "Fri", "Sat", and "Sun".

Inserting with “before” & “after”• Use insert and before keywords to insert an element

before an element at a given index. insert "Thu" before days[2];// The sequence now contains: "Mon", "Tue", "Thu", "Fri", "Sat", "Sun".

insert "wed" after days[1];// The sequence now contains: "Mon", "Tue", "Wed", "Thu", "Fri",// "Sat", and "Sun".

Deleting Items from a Sequence • The delete and from keywords make it easy to delete

items from a sequencedelete "Sun" from days;// The sequence now contains: "Mon", "Tue", "Wed", "Thu", "Fri", Sat".• You can also delete an element from a specific index

position.delete days[0];// The sequence now contains: "Tue", "Wed", "Thu", "Fri", Sat".• To delete all items from a sequence, use the delete

keyword followed by the name of the sequence: delete days;

Reversing Items in a Sequence • Reverse items in a sequence using the reverse

operator:var nums = [1..5];reverse nums; // returns [5, 4, 3, 2, 1]

Comparing Sequences • Sequences are compared for equality by value: if their

lengths are equal, and their items are equal, then they are equal. var seq1 = [1,2,3,4,5];var seq2 = [1,2,3,4,5];println(seq1 == seq2); // prints true

Sequences Slices• Sequence slices provide access to portions of a

sequence. • seq[a..b] - items between index a and index b

// weekend sequence consisting of only the items "Sat" and "Sun". var days = ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"];var weekend = days[5..6];• seq[a..<b] - between index a inclusive and index b

exclusive// weekdays sequence consisting of the items "Mon" through "Fri"var days = ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"];var weekdays = days[0..<5];

Sequences Slices• seq[a..] - all items from index a through the end of the

sequence// weekend sequence consisting of only the items "Sat" and "Sun". var days = ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"];var weekend = days[5..];

• seq[a..<] - everything from index a to the end of the sequence, excluding the last element. // sequence consisting of the items "Mon" through "Sat". var days = ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"];var days2 = days[0..<];

FunctionsFunctions

What is a Function?• A function is an executable block of code that performs

a specific task• Function code does not execute until it is explicitly

invoked> This makes it possible to run a function from any location

within your script. It does not matter if the function invocation is placed before or after the function definition

add(); // Invoke add function

function add() { result = numOne + numTwo; println("{numOne} + {numTwo} = {result}");}

>

Passing Arguments to Functions• Script functions may also be defined to accept

arguments. var result;

add(100,10);

function add(argOne: Integer, argTwo: Integer) { result = argOne + argTwo; println("{argOne} + {argTwo} = {result}");}

Returning Values from Functions• A function may also return a value to the code that

invokes itfunction add(argOne: Integer, argTwo: Integer) : Integer { result = argOne + argTwo; println("{argOne} + {argTwo} = {result}"); return result;

}

OperatorsOperators

Operators in JavaFX Script• Operators are special symbols that perform specific

operations on one or two operands, and then return a result.

• The JavaFX Script programming language provides> assignment operators> arithmetic operators> unary operators> equality and relational operators> conditional operators> type comparison operator.

Assignment Operators • Use it to assign the value on its right to the operand on

its left: result = num1 + num2;days = ["Mon","Tue","Wed","Thu","Fri"];

Arithmetic Operators • Use it to perform addition, subtraction, multiplication,

and division. • The mod operator divides one operand by another and

returns the remainder as its result// + (additive operator)// - (subtraction operator)// * (multiplication operator)// / (division operator)// mod (remainder operator)

result = 10;result = result mod 7; // result is now 3

Compound assignments var result = 0;

result += 1;println(result); // result is now 1

result -= 1;println(result); // result is now 0

result = 2;result *= 5; // result is now 10println(result);

result /= 2; // result is now 5println(result);

Unary Operators // - Unary minus operator; negates a number // ++ Increment operator; increments a value by 1 // -- Decrement operator; decrements a value by 1 // not Logical complement operator; inverts the value of a boolean

var result = 1; // result is now 1

result--; // result is now 0println(result);

result++; // result is now 1println(result);

result = -result; // result is now -1println(result);

var success = false;println(success); // falseprintln(not success); // true

Type Comparison Operator• Use it to determine if an object is an instance of a

particular class: def str1="Hello";println(str1 instanceof String); // prints true

def num = 1031;println(num instanceof java.lang.Integer); // prints true

ExpressionsExpressions

Expression in JavaFX Script• Expressions are pieces of code that evaluate to a result

value, and that can be combined to produce "bigger" expressions.

• The JavaFX Script programming language is an expression language, which means that everything, including loops, conditionals, and even blocks, are expressions.

• In some cases (such as while expressions) the expressions have Void type, which means they don't return a result value.

Types of Expression• Block expression• if expression• Range expression• for expression• while expression• break and continue expression• throw, try, catch, and finally expression

Block Expression • A block expression consists of a list of declarations or

expressions surrounded by curly braces and separated by semicolons.

• The value of a block expression is the value of the last expression. > If the block expression contains no expressions, the block

expression has Void type. > Note that var and def are expressions.

Example: Block Expression

var nums = [5, 7, 3, 9];var total = { var sum = 0; for (a in nums) { sum += a }; sum;}println("Total is {total}."); // Total is 24.

if Expression • if (booleanExpression) then a else b• if (booleanExpression) a else b• if (booleanExpression) { a } else { b }

for Expression • for (i in sequence) { ... }

Range Expression • By default the interval between the values is 1, but you

can use the step keyword to specify a different interval.var num = [0..5];

// Use step keyword to specify a different intervalvar nums = [1..10 step 2]; // [ 1, 3, 5, 7, 9 ]println(nums);

// descending rangevar nums = [10..1 step -1]; // [ 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 ]println(nums);

Access ModifiersAccess Modifiers

Access Modifiers• Allow you to set various levels of visibility for your

variables, functions, and classes (like in Java) • Access modifiers> Default Access> The package Access Modifier> The protected Access Modifier> The public Access Modifier> The public-read Access Modifier> The public-init Access Modifier

1

JavaFXJavaFXGUI BasicsGUI Basics

1

Quick JavaFX GUI Quick JavaFX GUI OverviewOverview

User Interface Elements• Standard UI components you can create using the

javafx.ext.swing package.

Colors• Color patterns for all constants of the

javafx.scene.paint.Color class

Shapes and Fill Styles• javafx.scene.shape and javafx.scene.paint packages

Text• Different formatting styles applied to the same text

string

Effects• Effects can be applied to the JavaFX UI elements

Transformation• Transformations can be performed for the graphics,

images, or text

Layout• There are several methods of laying out UI elements

using the javafx.scene.layout package.••

Cursors• Different views of cursor you can apply to any UI

element

Using Declarative SyntaxUsing Declarative Syntax(for Creating GUI)(for Creating GUI)

Why Declarative Syntax for Building GUI? • Because the structure of declared objects in the code

reflects the visual structure of the scene graph, and this enables you to understand and maintain the code easily.

• The order of elements you declare in the code matches the order in which they appear in the application.

Step by Step Process ofStep by Step Process ofCreating a Simple GUICreating a Simple GUI

Step by Step Process of Creating a simple GUI• JavaFX application that renders a green rounded

rectangle and a white circle with red outline on the top of the rectangle

Step by Step Process of Creating a GUI1.Add necessary imports2.Create an Application window3.Set the Scene4.Create a Rectangle5.Create a Circle6.Change the code (so that the Circle gets underneath

the Rectangle)

1. Add Necessary Importsimport javafx.stage.Stage; // required to render a window import javafx.scene.Scene; // required to display a circle and // rectangle on a windowimport javafx.scene.shape.Rectangle; // required to render the rectangle import javafx.scene.paint.Color; // required to fill and stroke the // rectangle and circle with colorimport javafx.scene.shape.Circle; // required to render the circle

2. Create an Application Window• In order to display the graphics, you need to create

a window through Stage object literal// Create a Stage object literal. Stage is required to render any object.// The window should be big enough to display all of the rectangle and // the circle. In this example, the window is a rectangle of 249 by 251// pixels. To create a window of this size, with a "Declaring is Easy" title,// declare these values within the curly brackets using the following code:

Stage { title: "Declaring Is Easy!" width: 249 height: 251 visible: true}

3. Set the Scene • Within the stage, set the scene to hold Node objects

such as a circle or a rectangle• The scene is a root area where you place objects of

the node type. • The scene has content variable that is used to hold

the nodes. • There are many different kinds of nodes, such as

graphical objects, text, and GUI components.

3. Set the Scene (Continued)

// The content of the window becomes filled with white because // white is a default fill color for a scene. The scene is placed on top // of the window.

Stage {

... scene: Scene { content: [ ] } }

4. Create a RectangleStage { ... scene: Scene { content: [ // The x and y instance variables specify the pixel location of the // rectangle, arcWidth and arcHeight define the roundness of // corners, and the fill variable defines the color that fills the rectangle. Rectangle { x: 45 y: 35 width: 150 height: 150 arcWidth: 15 arcHeight: 15 fill: Color.GREEN } ] } }

5. Create a CircleStage { ... scene: Scene { content: [ Rectangle { ... }, // Because the rectangle is declared before any other objects, it is painted // first. The rectangle will be behind any other objects painted later. Circle{ centerX: 118 centerY: 110 radius: 83 fill: Color.WHITE stroke: Color.RED } ] } }

6. Place Circle Underneath RectangleStage { ... scene: Scene { content: [ // Place the circle underneath the square. To do so, switch the order // of the circle and square Circle{ .... }, Rectangle { ... } ] } }

JavaFX ApplicationJavaFX ApplicationStructureStructure

Stage• Top-level container for a scene> Contains only one Scene

• Potentially represented by> JFrame on desktop> JApplet on web page> SVG player on mobile

• Defines the characteristics like title, width, height, location, handling exit, etc

Example: StageStage { title: "Welcome to JavaFX!" scene: Scene { content: [ Text { content: "Hello World!" x:25 y:25 fill: Color.BLACK font: Font{ size: 32 } } ] }}

Scene• Canvas upon which Scene Graph is displayed • Can set multiple CSS stylesheets• Can set background color (or set to null)• Can set canvas width/height

Scene GraphScene Graph

What is Scene Graph?• The scene graph is a tree-like data structure which

defines a hierarchy of graphical objects in a scene. • A single element in the scene graph is called a node.> Each node has one parent except for the root node, which

has no parent. > Each node is either a leaf node or a branch. > A leaf node has no children. > A branch node has zero or more children.

JavaFX Architecture

Graphics hardware

Java 2D

Effects

Project Scene Graph

JavaFX Script SoftwareModels a GUI part of a JavaFX application

Basic Graphical Objects• Graphical objects as examples of Nodes> Text, geometric shapes, text, Swing components

• Some common attributes in nodes> Transformation – translate, shear, rotate, scale> Clip – displaying only part of the node based on a geometric

shape> Effect – type of effect, eg. blurring, shadowing, to apply> Events – mouse, keyboard> Opacity – setting the translucency

What is Scene Graph?• A hierarchical representation of graphical objects> Tree like structure> Basis of JavaFX graphics engine• Scene graph elements> Nodes – images, text, Swing widgets> State – visibility, opacity, transformation> Events – mouse, keyboard, node updates> Animation – varying properties over time• A scene graph knows how to render itself!!> JavaFX scene graph engine is available at

http://scenegraph.dev.java.net> Usable from Java

Scene Graph: Group• Group stands a set of Nodes which may have same

effect• Group itself is a Node, so can be nested

Scene Graph: Group Group {

transforms: Translate {x:15, y, 15

}content: [

Text {x: 10, y: 50font: Font: {

size: 50}content: “Hello World”

}Circle {

centerX: 100, centerY: 100radius: 40fill: Color.BLACK

}]

}

Group

CircleText

x:15y:15

ShapesShapes

Shapes• Arc• Circle• Ellipse• Line• Path• Polygon

• Rectangle• stroke• strokeWidth• fill• smooth

Geometric Shapes• Arc, ellipse, line, polygon, circle, rectangle• Very similar to textCircle { centerX: 70, centerY: 70 radius: 50 fill: Color.PINK stroke: Color.RED strokeWidth: 3 strokeDashArray: [ 7 ] strokeDashOffset: 2}

Custom Shapes• Two ways of defining custom shapes> Combining existing shapes> Drawing a totally new shape

• Combine existing shape with ShapeIntersect or ShapeSubtract

> Either add or subtract from shape

• Draw new shapes with Path and path elements> Path elements include MoveTo, ArcTo, HLine, VLine, QuadCurve,

etc.• Can be manipulated like a regular geometric shape

Example – ShapeIntersect ShapeIntersect {

transforms: [ Translate { x: 170 } ]fill: Color.LIGHTGREENstroke: Color.GREENstrokeWidth: 3//Union of the 2 shapesa: [rectangle diamond ]

}

Example – PathPath {

fill: Color.LIGHTGRAYstroke: Color.GRAYstrokeWidth: 3

elements: [ MoveTo { x: 15 y: 15 }, ArcTo { x: 50 y: 10 radiusX: 20

radiusY: 20 sweepFlag: true}, ArcTo { x: 70 y: 20 radiusX: 20

radiusY: 20 sweepFlag: true}, ArcTo { x: 50 y: 60 radiusX: 20

radiusY: 20 sweepFlag: true}, ArcTo { x: 20 y: 50 radiusX: 10

radiusY: 5 sweepFlag: false}, ArcTo { x: 15 y: 15 radiusX: 10

radiusY: 10 sweepFlag: true}, ]}

Other Graphical ObjectsOther Graphical Objects

Text• x, y, TextOrigin• By default, text positioned such that (x, y) is left

baseline• Fonts can be specified on Text• Favor “fill” over “stroke”• Supports multiple text• Use Alignment to align multi-line text• To center text, compute the center via layout bounds

Text• Defines a node for displaying textText {

effect: DropShadow {offsetX: -10offsetY: -10

}font: Font {

name: “DirtyBakersDozen”size: 50

}fill: Color.ROYALBLUEstroke: Color.BLUE, strokeWidth: 3x: 15, y: 80content: "Hello World"

}

Image• ImageView node shows images• Image represents an in-memory image• Image can load images in foreground thread or

background thread• Both ImageView and Image can scale> Preserve ratio> Fit within a specific width/height> When fit on Image level, keeps smaller image in memory

ImagesImageView = ImageView {

clip: Rectangle {

y: 30 x: 50

width: 350 height: 100

}

image: Image { url: "..."}

}

TextBox• Used for text input• Use CSS to style the TextBox• “text” is changed to reflect the actual text in the TextBox• “value” is changed when the text is “committed” via

ENTER, TAB, etc• “action” function is invoked when ENTER is pressed• “columns” specifies the preferred width based on the

font size and number of characters to display

EffectsEffects

How Effect Works• javafx.scene.effect package API. • All of the core filter effect classes extend the abstract

javafx.scene.effect.Effect base class. • Any Effect instance can be applied to a scene graph

Node by setting the Node.effect variable. • Each Effect subclass exposes a small number of

variables that control the visual appearance of the Node.

• In addition, most Effect subclasses provide one or more input variables that can be used to "chain" effects

Variables In a Effect Class• Each variable is generally documented with default,

minimum, maximum, and identity values, which makes it easy to see the acceptable range of values.

• Developer only need to concern yourself with turning the values of these variables.

• The effects framework does all the heavy lifting for you, such as painting the Node into an offscreen image at the appropriate resolution, manipulating the pixels in one of the CPU and/or GPU accelerated backends, and automatically repainting the affected portion of the scene.

Effects:Effects:DropShadowDropShadow

Example: DropShadow class• DropShadow class provides 5 variables> color: The shadow Color>default: Color.BLACK

> offsetX: The shadow offset in the x direction, in pixels. >default: 0.0

> offsetY: The shadow offset in the y direction, in pixels. >default: 0.0

> radius: The radius of the shadow blur kernel.>default: 10.0, max: 63.0

> spread: The spread of the shadow.>default: 0.0, max: 1.0, min: 0.0

Example: DropShadow Text { effect: DropShadow { offsetY: 3 color: Color.color(0.4, 0.4, 0.4) }; ... }, Circle { effect: DropShadow { offsetY: 4 }, ... }

Example: DropShadow Text { effect: DropShadow { offsetY: 3 color: Color.GREEN radius: 20.0 }; ... }, Circle { effect: DropShadow { offsetX: 10 offsetY: 20 color: Color.BLUE radius: 30.0 } ... }

Effects:Effects:LightingLighting

Lighting Effecteffect: Lighting{

surfaceScale: 7light: DistantLight{

azimuth: 90elevation: 30

}}

effect: Lighting{surfaceScale: 7light: SpotLight {

x: 0 y :0 z: 50pointsAtX: 10pointsAtY: 10 pointsAtZ: 0color: Color.YELLOW

}}

Effects:Effects:PerspectiveTransformPerspectiveTransform

PerspectiveTransform Class• Used to provide a "faux" three-dimensional effect for

otherwise two-dimensional content. Group { effect: PerspectiveTransform { ulx: 10 uly: 10 urx: 310 ury: 40 lrx: 310 lry: 60 llx: 10 lly: 90 } cache: true content: [ Rectangle { x: 10 y: 10 width: 280 height: 80 fill: Color.BLUE }, Text { x: 20 y: 65 content: "Perspective" fill: Color.YELLOW font: Font.font(null, FontWeight.BOLD, 36); }, ]}

Effects:Effects:Linear GradientsLinear Gradients

Linear Gradients• startX, startY, endX, endY> Define the direction of the gradient> On the unit square

• Stops define each step in the gradient.• Each stop> Has an offset between 0...1> Has a color

Effects:Effects:Glow, Reflection,Glow, Reflection,GaussianBlurGaussianBlur

Some Effects Supported In JavaFXeffect: SepiaTone { level: 0.5 }

effect: Glow { level: 0.7 }

effect: GaussianBlur {input: SepiaTone {

level: 0.5 }radius: 10.0

}

effect: Reflection { fraction: 0.7 }

Original image

1

JavaFX Script JavaFX Script Language: Data Language: Data binding & Triggersbinding & Triggers

1

What is Binding?What is Binding?

What is & Why (Data) Binding?• Data binding refers to the language feature of JavaFX

script of creating an immediate and direct relationship between two variables,

• Data binding is one of the most powerful features of the JavaFX Script programming language.

• In most real-world programming situations, you will use data binding to keep an application's Graphical User Interface (GUI) in sync with its underlying data.

How Binding Works• Cause and effect – responding to changes• bind operator allows dynamic content to be expressed

declaratively• Dependency based evaluation of any expression• Automated by the JavaFX runtime rather than manually

wired by the programmer• Eliminates the listener pattern

Binding• The bind keyword associates the value of a target

variable with the value of a bound expression. • The bound expression can be a simple value of > some basic type> an object> outcome of a function> outcome of an expression.

Binding to a VariableBinding to a Variableof Basic Typeof Basic Type

Binding to a Basic Typevar x = 0;// Bind variable x to variable y.// Note that we have declared variable y as a def. This prevents// any code from directly assigning a value to it (yet its value is// allowed to change as the result of a bind).You should use this // same convention when binding to an objectdef y = bind x;x = 1;println(y); // y now equals 1x = 47;// Because the variables are bound, the value of y // automatically updates to the new value. println(y); // y now equals 47

Binding to an ObjectBinding to an Object

Binding to an Objectvar myStreet = "1 Main Street";var myCity = "Santa Clara";var myState = "CA";var myZip = "95050";

def address = bind Address { street: myStreet; city: myCity; state: myState; zip: myZip;};

println("address.street == {address.street}"); // prints “1 Main Street”// By changing the value of myStreet, the street variable inside the address object // is affected. Note that changing the value of myStreet actually causes a new// Address object to be created and then re-assigned to the address variable. myStreet = "100 Maple Street";println("address.street == {address.street}"); // prints “100 Maple Street”

Binding to an Objectvar myStreet = "1 Main Street";var myCity = "Santa Clara";var myState = "CA";var myZip = "95050";

// To track changes without creating a new Address object, bind directly to the // object's instance variables instead: def address = bind Address { // You can omit bind on this line street: bind myStreet; city: bind myCity; state: bind myState; zip: bind myZip;};

println("address.street == {address.street}"); // prints “1 Main Street”myStreet = "100 Maple Street";println("address.street == {address.street}"); // prints “100 Maple Street”

Binding to a FunctionBinding to a Function

Binding and Functions• There is a difference between “binding to a bound

function” vs. “binding to a non-bound function”. > Binding to a “bound function” - change for the value of a non-

function-argument invoke the function> Binding to a “non-bound function” - change for the value of a

non-function-argument does not invoke the function

Definition of a Bound Functionvar scale = 1.0;

// makePoint is a bound function. It will be invoked even when a value of // non-function-arugment such as scale changes. If you remove bound// keyword, then, the change of the value of scale does not invoke the// function.bound function makePoint(xPos : Number, yPos : Number) : Point { Point { x: xPos * scale y: yPos * scale }}

class Point { var x : Number; var y : Number;}

Invocation of a Bound Function// Code in the previous slide

// The bind keyword, placed just before the invocation of// makePoint, binds the newly created Point object (pt) to the outcome of the// makePoint function. var myX = 3.0;var myY = 3.0;def pt = bind makePoint(myX, myY);println(pt.x); // 3.0

myX = 10.0;println(pt.x); // 10.0

scale = 2.0;println(pt.x); // 20.0

TransformationTransformation

Transformation class• Provides functions to perform > rotating> scaling> shearing> translation

Rotate Transformation• Rotates coordinates around an anchor pointStage { title: "Welcome to JavaFX!" scene: Scene { width: 200 height: 200 content: [ Rectangle { transforms: Rotate { angle: bind angle pivotX: 10 pivotY: 10 } ... } ] }}

Scale Transformation• Scales coordinates by the specified factorsStage { title: "Welcome to JavaFX!" scene: Scene { fill: Color.LIGHTBLUE content: [ Group { translateX: 55 translateY: 10 content: [ Circle { ... }, Text { content: "Duke" }, ImageView { ... } ] transforms: bind Transform.scale(scale, scale)

} // Group ] // content

}

Shear Transformation• Shears coordinates by the specified multipliersStage { title: "Transformation - Shear" scene: Scene { content: [ Rectangle { transforms: Shear { x: bind shearX y: bind shearY } x: 40 y: 10 width: 100 height: 50 fill: Color.GREEN onMouseEntered: function( e: MouseEvent ):Void { shearX = -0.8; } onMouseExited: function( e: MouseEvent ):Void { shearX = -0.35; } } ] }}

Translation Transformation• Translates coordinates by the specified factorsStage { title: "Transformation - Translate" width: 100 height: 100 scene: Scene { content: [ Rectangle { transforms: Translate { x: bind translateX y: bind translateY } x: 10 y: 10 width: 20 height: 20 fill: Color.GREEN onMouseEntered: function( e: MouseEvent ):Void { translateX = 20; translateY = 30 } onMouseExited: function( e: MouseEvent ):Void { translateX = 0.0; translateY = 0.0; } } ] }}

InteractionsInteractions

Handling Events• All nodes have either mouse or keyboard events> Override the appropriate method

• Mouse events – onMouseXXXX()> XXXX = Entered, Exited, Pressed, Dragged, Moved, Clicked,

Released, WheelMoved• Keyboard events – onKeyboardXXXX()> XXXX = Pressed, Released, Typed

• Indicate interactivity by changing cursor> Set the cursor attribute

Example: Handling Events• Mouse events change the color of an rectanglevar rectangle:Rectangle = Rectangle { x: 20, y: 10 width: 150, height: 70 arcWidth: 50, arcHeight: 50 fill: Color.LIGHTBLUE stroke: Color.ROYALBLUE strokeWidth: 3 onMouseEntered: function( e: MouseEvent ):Void { rectangle.fill = Color.WHITESMOKE; } onMouseExited: function( e: MouseEvent ):Void { rectangle.fill = Color.LIGHTBLUE; }}

Drag and DropDrag and Drop

Drag and Drop (using sceneX, sceneY)• Drag an object around the screenvar startX = 0.0;var startY = 0.0;var rectangle:Rectangle = Rectangle { x: 0 y: 30 width: 150 height: 70 arcWidth: 50, arcHeight: 50 fill: Color.LIGHTBLUE stroke: Color.ROYALBLUE strokeWidth: 3 cursor: Cursor.HAND onMousePressed: function( e: MouseEvent ):Void { startX = e.sceneX - rect.translateX; startY = e.sceneY - rect.translateY; } onMouseDragged: function( e: MouseEvent ):Void { rect.translateX = e.sceneX - startX; rect.translateY = e.sceneY - startY; }}