The Java Fx Platform – A Java Developer’S Guide

Post on 15-May-2015

5.576 views 0 download

Tags:

description

Presented at Devoxx 2009 for the JavaFX Univerity Session. Also available online at Parleys.com.

Transcript of The Java Fx Platform – A Java Developer’S Guide

The JavaFX Platform – A Java Developer’s Guide

Stephen ChinInovis, Inc.

About Your PresenterDirector SWE,

Inovis, Inc.> MBA> Belotti Award> Uber

ScrumMaster> XP Coach> Agile

Evangelist

Open-Source JavaFX Hacker

> WidgetFX> JFXtras> FEST-JavaFX> Piccolo2D> Java Champion> JavaOne Rockstar> JUG Leader> Pro JavaFX Author

2

Motorcyclist

Family Man

LearnFX and Win at Devoxx

Tweet to answer:> @projavafxcourse your-answer-here

3

Part 1 - JavaFX Crash Course

var x = ['x','o','v','e','d','x'];insert x[5] before x[0];println("{reverse x[0..<]}");@projavafxcourse answer

1. Download JavaFX> http://javafx.com/

5

2. Run Your IDE

3. Write Your First App

> NetBeans (bundled)> Eclipse – Exadel JavaFX Studio

> Step-by-Step Demo

var x = ['x','o','v','e','d','x'];insert x[5] before x[0];println("{reverse x[0..<]}");@projavafxcourse answer

Hello Devoxx!

Hello Devoxx!: Creating a Stage

Stage { title: "Hello Devoxx!" scene: Scene { content: [ "..." ] }}

6

var x = ['x','o','v','e','d','x'];insert x[5] before x[0];println("{reverse x[0..<]}");@projavafxcourse answer

Hello Devoxx!: Displaying Images

ImageView { image: Image { url:

"http://www.javoxx.com/download/attachments/1706305/Devoxx09.jpg"

} opacity: .5}

7

var x = ['x','o','v','e','d','x'];insert x[5] before x[0];println("{reverse x[0..<]}");@projavafxcourse answer

Hello Devoxx!: RSS Feed

var items:Item[];RssTask { interval: 30s; location:

"http://search.twitter.com/search.rss?q=devoxx"

onItem: function(item) { insert item into items; }}.start();

8

Hello Devoxx!: VBox Layout

var textBox:VBox;

textBox = VBox { layoutX: 40 layoutY: 40 spacing: 20 content: "..."}

9

Hello Devoxx!: Displaying Text

content: bind for (item in items) { Text { textOrigin: TextOrigin.TOP textAlignment: TextAlignment.JUSTIFY wrappingWidth: 520 font: Font.font(null, FontWeight.BOLD, 18) content: item.title }}

10

Hello Devoxx!: Animating Graphics

var transTransition = TranslateTransition { duration: 2m node: bind textBox fromY: 600 toY: -4000 interpolator: Interpolator.LINEAR repeatCount: Timeline.INDEFINITE}transTransition.play();

11

Hello Devoxx!: Playing Audio

MediaPlayer { autoPlay: true repeatCount: MediaPlayer.REPEAT_FOREVER media: Media { source:

"http://blogs.sun.com/roller/resources/dcb/Java.mp3"

}}

12

?

13

Hello Devoxx! Demo

Resource: JavaFX API Documentation

14

http://java.sun.com/javafx/1.2/docs/api/

15

Part 2 - Comparing JavaFX and Java

var x = ['x','o','v','e','d','x'];insert x[5] before x[0];println("{reverse x[0..<]}");@projavafxcourse answer

Language Similarities

Java is…> Statically typed> Compiled to bytecodes> Runs on the JVM> Has a large library

JavaFX is…> Statically typed> Compiled to bytecodes> Runs on the JVM> Can call Java libraries

16

Language Differences

17

JavaFX• Type Inferencing• Closures• Binding• Sequences• Animation Syntax

Java• Annotations• Generics• Multi-Threading

Integrating JavaFX and Java

> Calling Java from JavaFX Can call Java interface or classes directly Automatic conversion to and from Arrays and

Collections Can even extend Java interfaces and classes

> Calling JavaFX from Java Easiest way is to create a Java interface that

JavaFX extends Can invoke JavaFX as a script and get results back

18

Datatype SupportDataType Java Equivalent Range Examples

Boolean boolean true or false true, false

Integer int -2147483648 to 2147483647 2009, 03731, 0x07d9

Number Float 1.40×10-45 and 3.40×1038 3.14, 3e8, 1.380E-23

String String N/A "java's", 'in"side"er'

Duration <None> -263 to 263-1 milliseconds 1h, 5m, 30s, 500ms

Character char 0 to 65535 0, 20, 32

Byte byte -128 to 127 -5, 0, 5

Short short -32768 to 32767 -300, 0, 521

Long long -263 to 263-1 2009, 03731, 0x07d9

Float float 1.40×10-45 and 3.40×1038 3.14, 3e8, 1.380E-23

Double double 4.94×10-324 and 1.80×10308 3.14, 3e231, 1.380E-123

19

JavaFX Operators

Operator Meaning Precedence Examples ++ Pre/post increment 1 ++i, i++ -- Pre/post decrement 1 --i, i-- not Boolean negation 2 not (cond) * Multiply 3 2 * 5, 1h * 4 / Divide 3 9 / 3, 1m / 3 mod Modulo 3 20 mod 3 + Add 4 0 + 2, 1m + 20s - Subtract (or negate) 4 (2) -2, 32 -3, 1h -5m

20

> Multiplication and division of two durations is allowed, but not meaningful

> Underflows/Overflows will fail silently, producing inaccurate results

> Divide by zero will throw a runtime exception

JavaFX Operators (continued)

Operator Meaning Precedence Examples == Equal 5 value1 == value2, 4 == 4 != Not equal 5 value1 != value2, 5 != 4 < Lessthan 5 value1 < value2, 4 < 5 <= Lessthanorequal 5 value1 <= value2, 5 <= 5 > Greater than 5 value1 > value2, 6 > 5 >= Greater than or equal 5 value1 >= value2, 6 >= 6 instanceof Is instance of class 6 node instanceof Text as Typecast to class 6 node as Text and Boolean and 7 cond1 and cond2 or Boolean or 8 cond1 or cond2 += Add and assign 9 value += 5 -= Subtract and assign 9 value -= 3 *= Multiply and assign 9 value *= 2 /= Divide and assign 9 value /=4 = Assign 9 value = 7

21

Access Modifiers

Modifier Name Description<default> Script only access Only accessible within the same script file

package Package access Only accessible within the same package

protected Protected access Only accessible within the same package or by subclasses.

public Public access Can be accessed anywhere.

public-read Read access modifier Var/def modifier to allow a variable to be read anywhere

public-init Init access modifier Var/def modifier to allow a variable to be initialized or read anywhere

22

Data Binding

> A variable or a constant can be bound to an expression var x = bind a + b;

> The bound expression is remembered> The dependencies of the expression is watched> Variable is updated

Regular binding: when dependencies change values

Lazy binding: when the variable is accessed var x = bind lazy a+ b;

23

What Bind Updates

var x = bind if(a) then b else c> x is updated if a or b or c changes

var x = bind for (i in [a..b]) { i * i }> Not everything is recalculated> If a = 1 and b = 2, x is [1, 4]> If b changes to 3, only the added element is

calculated

24

1 4 9

Binding to Expressions

> Binding to a block> Bound block may contain any number of defs

followed by one expression> Dependencies of block is backtraced from the

expression> Binding to function invocation expression

Regular function: dependencies are parameters Bound function: backtraced from final expression

inside function

25

Binding to Object Literals

var a = 3; var b = 4;var p = bind Point { x: a, y: b };var q = bind Point { x: bind a, y: b };var r = bind Point { x: bind a, y: bind b };

> When a changes: p gets a new instance of Point q and r keep the old instance with a new x value r will never get a new instance of Point

(the outer bind in r is useless)

26

Binding to FunctionsStage { def cModel = CircleModel {}; var sliderRef:Slider; scene: Scene { content: [ Circle { radius: bind cModel.diameter / 2 }, Text { content: bind "Diameter: {%3.0f cModel.diameter}" }, Text { content: bind "Area: {%3.2f cModel.getArea()}" }, sliderRef = Slider { value: bind cModel.diameter with inverse}]}}

27

http://learnjavafx.typepad.com/weblog/javafx_app_deployment/

class CircleModel { var diameter:Number; bound function getArea():Number { Math.PI * Math.pow(diameter / 2, 2); }}

JavaFX Sequences

> Represents collections of homogeneous data> A fundamental container data type> Rich set of language facilities> Contributor to declarative syntax> Automatic conversion to and from Java Arrays

and Collections

28

Creating Sequences

> Explicit sequence expression [1, 3, 5, 7, 9]

> Elements are separated by commas> Comma may be omitted if element ends with

brace

29

1 3 5 7 9

Creating Sequences> Numeric sequence with range expressions:

[1..10]> Can have a step:

[1..10 step 2] [0.0..0.9 step 0.1]

> Can be decreasing: [10..1 step -3]

> Beware of step that goes opposite direction: [10..1] is []

> Exclusive right end [1..<5]

30

1 2 3 4 5 6 7 8 9 10

1 3 5 7 9

0 .1 .2 .3 .4 .5 .6 .7 .8 .9

10 7 4 1

1 2 3 4

Getting Information from Sequences

ints = [1, 3, 5, 7, 9]

> sizeof ints is 5> ints[0] is 1, ints[1] is 3, ..., ints[4] is 9> ints[-1] is 0 (default value of Integer), so is

ints[5]

> For a sequence of objects, the default is null

31

1 3 5 7 9[0] [1] [2] [3] [4]

Getting Slices From Sequences

ints = [1, 3, 5, 7, 9]

> ints[0..2] is [1, 3, 5]> ints[0..<2] is [1, 3]> ints[2..] is [5, 7, 9]> ints[2..<] is [5, 7]> ints[2..0], ints[-2..-1], ints[5..6] are all []s

32

1 3 5 7 9[0] [1] [2] [3] [4]

Getting Subsets from Sequences

ints = [1, 3, 5, 7, 9]

> ints[k | k > 6] is: [7, 9] (k > 6 is a condition)

> ints[k | indexof k < 2] is: [1, 3]

> ints[k | k > 10] is: []

33

1 3 5 7 9[0] [1] [2] [3] [4]

Inserting into Sequences

ints = [1, 3, 5, 7, 9]

insert 20 into ints

insert 30 before ints[2]

insert 40 after ints[4]

insert [50, 60] into ints

34

1 3 5 7 9

1 3 5 7 9

1 3 5 7 9

20

2030

1 3 5 7 9 2030 40

1 3 5 7 9 2030 40 50 60

Deleting from Sequences

> ints = [1, 3, 5, 7, 9]

> delete 7 from ints

> delete ints[0]

> delete ints[0..1]

> delete ints: ints becomes []

35

1 3 5 7 9

1 3 5 9

3 5 9

9

1 3 5 7 9

Sequence Puzzlers

What is the size of this sequence:> [1..10 step -1]

What does this evaluate to:> [10..<20 step 2][k|k>17]

What is the size of this sequence:> sizeof [20..1 step -3]

36

FX1

2

3

A: 0

A: 1

A: [18]

Reference: JavaFX RefCard

37

http://refcardz.dzone.com/refcardz/

Demo by Tor Norbye

38

JavaFX Builder Tool

?

39

JavaFX 1.2 Layouts

40

JavaFX 1.2 Custom Layouts

> Container> Panel

> Both Extend Parent> Container creates layouts by extension> Panel creates layouts by declaration

Who is My Representative?

41

Web Service Integration

42

Calling a REST Service

> REST URL:http://whoismyrepresentative.com/

getall_mems.php?zip=90210&output=json> Output:{ "results": [ { "type": "rep", "name": "Henry A. Waxman", "party":

"D", "state": "CA", "district": "30", "phone": "(202) 225-3976", "office": "2204 Rayburn", "link": "http://www.henrywaxman.house.gov/" }

]}

Making an HttpRequest

req = HttpRequest { method: HttpRequest.GET location: url onInput: parseResponse onDone: function() { if (req.responseCode != 200) { message = req.responseMessage; } else if (sizeof senators == 0 and sizeof representatives == 0) { message = "No members found for {zipcode}"; } } onException: function(ex: java.lang.Exception) { println("Exception: {ex.getClass()} {ex.getMessage()}"); }}req.start();

43

Using the Pull Parser

while (parser.event.type != PullParser.END_DOCUMENT) { parser.seek( "type" ); if (parser.event.type == PullParser.START_VALUE) { parser.forward(); if (parser.event.text == "rep") { var rep = Representative{} parseMemberOfCongress( rep, parser ); insert rep into representatives; } else if (parser.event.text == "sen" ) { var sen = Senator{} parseMemberOfCongress( sen, parser ); insert sen into senators;} } }

44

JavaFX Mobile Development

JavaFX Mobile Advantages

> Write Once, Run Anywhere Desktop, Mobile, Set-top Boxes (future)

> Large Embedded Base Built on top of Java ME platform

> Wide Range of Devices Runs on Feature Phones, Smart Phones Currently available for Windows Mobile devices

JavaFX Mobile Constraints

> Screen Size Your application has to be capable of adapting

to different screen sizes as small as 320 by 240.

> Common Profile Mobile applications are limited to the JavaFX

APIs that are part of the Common Profile, which is a subset of the Desktop Profile.

> Performance Mobile applications run on much less powerful

devices, so they have less CPU and memory resources available to work with.

Developing for the Common ProfilePackage Class(es) Affected Variables and Methods

javafx.ext.swing All All

javafx.reflect All All

javafx.scene Node effect, style

javafx.scene Scene Stylesheets

javafx.scene.effect All All

javafx.scene.effect.light All All

javafx.scene.shape ShapeIntersect All

javafx.scene.shape ShapeSubstract All

javafx.scene.text FontautoKern, embolden, letterSpacing, ligatures, oblique, position

javafx.stage AppletStageExtension All

javafx.util FXEvaluator All

javafx.util StringLocalizer All

Changes to Improve Hello Devoxx!

> It runs as is with no changes, but was not designed for the mobile format.

> We can do better:1. Replace all hard-coded sizes with a bind2. Scale the background image to the screen size3. Put an error up on network failure

> The improved version also works on the desktop.

49

Mobile Demo

Hello Devoxx!

JavaFX How-To’s

51

http://javafx.com/learn/howto.jsp

52

JFXtras – Open Source JavaFX Addons

http://jfxtras.org/

JFXtras Grid

53

Row

Row

JFXtras Grid

XGrid { effect: Reflection {} border: 20 vgap: 12 hgap: 12 rows: bind [ row([text, progressBar]), row([navigator, mediaGrid]) ]}

54

Media Explorer Example

55

JFXtras Borders

56

JFXtras Borders

Function:override function create() { XTitledBorder { id: "imageTitle“ title: file.getName() content: XFrameBorder { id: "imageFrame“ node: XImageView { preserveRatio: true smooth: true image: bind image } } }}

CSS:#imageTitle { position: "bottom"; justification: "center"; font: bold 12pt Serif; text-color: #000060;}#imageFrame { border-left-width: 12; border-top-width: 12; border-bottom-width: 20; border-right-width: 12; background-fill:

#00007020;}

57

59

MigLayout for JavaFX

60

Flow Wrap

Flexible Grid-Based Layout

MigLayout Constraints

“fill”

“gap”“flowy”

“wrap”

MigLayout { constraints: “fill, wrap”

// to be continued}

61

MigLayout { constraints: "fill, wrap" columns: "[][]" rows: "[][]4mm[]push[]" content: [ Label { text: "Email" layoutInfo: nodeConstraints( "ax right" ) } TextBox { layoutInfo: nodeConstraints( "growx, pushx" ) } Label { text: "Password" layoutInfo: nodeConstraints( "ax right" ) } TextBox { layoutInfo: nodeConstraints( "growx, pushx" ) } Button { text: "Login" layoutInfo: nodeConstraints( "skip, right" ) } Label { text: "This text is 'pushed' to the bottom" layoutInfo: nodeConstraints( "span" ) } ]}

62

JFXtras Shapes

63

Almond Intersection of two circles (Vesica Piscis) centerX, centerY, width

Arrow Arrow shape x, y, width, height, depth, rise

Asterisk Asterisk with rounded corners centerX, centerY, width, radius, beams, roundness

Astroid Hypocloid with four cusps centerX, centerY, radius

Balloon Rectangular shape with a tabx, y, width, height, arc, anglePosition, tabWidth, tabHeight, tabLocation, tabDisplacement

Cross Symmetrical cross shape centerX, centerY, width, radius, roundness

Donut Regular polygon with a hole centerX, centerY, innerRadius, outerRadius, sides

Lauburu Four comma-shaped heads centerX, centerY, radius

Continued…

JFXtras Shapes (continued)

64

MultiRoundRectangle Rectangle with configurable corners x, y, width, height, topLeftWidth/Height, topRightWidth/Height, bottomLeftWidth/Height, bottomRightWidth/Height

Rays Multiple rays extend from center centerX, centerY, rays, radius, extent, rounded

RegularPolygon Polygon with equal sides centerX, centerY, sides, radius

ReuleauxTriangle Curved triangle shape centerX, centerY, radius

RoundPin Cone with rounded top centerX, centerY, height, radius

Star2 Multipoint star centerX, centerY, innerRadius, outerRadius, count

ETriangle Equilateral triangle x, y, widthITriangle Isosceles triangle x, y, width, height

RTriangle Right trianglex, y, width, height, anglePosition

Sphere Challenge

66

Andres Almiray’s Weblog

“The following snapshot shows a couple of spheres drawn with GfxBuilder and FxBuilder, can you guess which one is which?…This is by no means a post to bash JavaFXrather to point out some of its deficiencies”

-- Andres Almiray (taken completely out of context)

http://www.jroller.com/aalmiray/entry/griffon_gfxbuilder_fxbuilder_side_by

Sphere Challenge – JavaFX Response

> Composition: RadialGradient for the Sphere Three additional RadialGradients for

the light sources A blurred shadow underneath

> Features: All Bound/Relative Coordinates Configurable –

Base, Ambient, Specular, Shine Colors Shadow Size and Height

Uses New JFXtras ColorUtil Library JavaFX Caching for High Performance

67

Will be shipped with JFXtras 0.6

The JavaFX Desktop Widget Platform

WidgetFX

WidgetFX Origins

71

72

Why WidgetFX Matters

Movie Widget Tutorial

Widget PropertiesName Type Inherited From Description

width Number Resizable Initial width of the widget.

height Number Resizable Initial height of the widget.

aspectRatio Number Widget If set, defines a fixed aspect ratio for the widget width and height.

content Node[] Group Visible children of the widget. Contains a sequence of Nodes.

74

Widget Definition

var widget: Widget;widget = Widget { width: 640 height: 352 aspectRatio: bind player.media.width / player.media.height content: bind player}

75

Load the Media

var source = "http://projavafx.com/movies/ elephants-dream-640x352.flv";

var player = bind SimpleMoviePlayer { media: Media { source: source } width: bind widget.width height: bind widget.height}

76

Run in Widget Runner

77

Widget Configuration PropertiesClass Name Type Description

BooleanProperty Boolean This class allows you to persist sequences of Booleans

BooleanSequenceProperty Boolean[] This class allows you to persist sequences of Booleans

IntegerProperty Integer This class allows you to persist Integers

IntegerSequenceProperty Integer[] This class allows you to persist sequences of Integers

LongProperty Long This class allows you to persist Longs

LongSequenceProperty Long[] This class allows you to persist sequences of Longs

NumberProperty Number This class allows you to persist Numbers

NumberSequenceProperty Number[] This class allows you to persist sequences of Numbers

StringProperty String This class allows you to persist Strings

StringSequenceProperty String[] This class allows you to persist sequences of Strings

78

Widget Configuration

widget = Widget { ... configuration: Configuration { properties: [ StringProperty { name: "source“ value: bind source with inverse } ] scene: Scene {…} // see next page }}

79

Widget Config Dialog

Scene { content: XGrid { rows: row([ Text { content: "Source URL:“ }, TextBox { columns: 30, value: bind source with inverse } ]) }}

80

Add an On-Replace Trigger

var player = bind SimpleMoviePlayer { media: Media { source: source } width: bind widget.width height: bind widget.height} on replace =oldPlayer { oldPlayer.player.stop();}

81

Widget Configuration (demo)

82

WidgetFX Contest Results!> 3rd Place

Infix WeatherWidget Larry Dickson

> 2nd Place RadioFX Yannick Van Godtsenhoven

> 1st Place ScreenshotFX Pär Dahlberg

83

JavaFXpert RIA Exemplar Challenge

> "Create an application in JavaFX that exemplifies the appearance and behavior of a next-generation enterprise RIA (rich internet application)".

> Grand Prize: $2,000 USD

> (split between a two-man graphics artist and application developer team)

> Deadline: 10 January, 2010> For more info: http://learnjavafx.typepad.com/

84

LearnFX and Win at Devoxx

85

Thursday’s Question

> HttpRequest {> location: http://steveonjava.com/> onResponseMessage: function(m) {> println(m); FX.exit()> }}.start();

> Launch LearnFX from my blog: http://steveonjava.com/> Or tweet @projavafxcourse answer

> 2:00PM Room 8 (right here!)

86

Sneak Preview of Thursday’s Session

87

88

Stephen Chinhttp://steveonjava.com/Tweet: steveonjava

Thank You

Thanks to my co-authors, Jim, Weiqi , and Dean for content included in this talk!