Java Fx Overview Tech Tour

download Java Fx Overview Tech Tour

If you can't read please download the document

description

JavaFX overview

Transcript of Java Fx Overview Tech Tour

  • 1. JavaFX - Rich GUIs Made Easy Carol McDonald Technology Evangelist

2. Agenda

  • JavaFX Script Language Overview

3. Advanced features

    • Graphics
  • 4. User Input

5. Animation 6. Media 7. Work with Restful Web Services

  • JavaFX Application Deployment

8. Summary and References 9. Overview of theJavaFX SDK 10. JavaFX Vision *

  • Rich Clients

11. Multiple devices JavaFX isTHEplatform forcreating and deliveringRich Internet Application sacross all the screens of your life 12. Targeting Developer/Designer Workflow

  • Working together with graphic designers to conceptualize the interface

Sean Wani (Graphic Designer) Karl May (Mashup author/builder) Amy Lewis (Suburban wife/mom) Tom Hammer (Media Editor) Saloni Sarin (Creative Director) Livleen (Student) Samir Arora (Business Professional) Adam Nielson (Web Master) Wayne Stidolph (Programmer) Rich Internet Apps + content Across desktop,mobile, TV, car Creative Community Consumers 13. Things You Can Build with JavaFX 14. 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.

15. 3-D Display Shelf With the PerspectiveTransform

  • ThePerspectiveTransformbuilt into JavaFX can be used to easily create 3-D effects

16. Demo: JavaFX Sample Apps from javafx.com 17. JavaFX Script

  • JavaFX Script source files are called scripts

18. Everything in JavaFX script is an expression 19. All blocks are expressions 20. The last line is the resultprintln( Hello World ) The result of the println expression is null 21. JavaFX Script Programming Language

  • Declarative, statically-typed scripting language

22. Facilitates rapid GUI development 23. Integrates with and Leverages Java Platform 24. Runs on Java Virtual Machine

  • Deployment options same as Java programs

25. Example of JavaFX Application Stage {title: "circle" width: 240 height: 200 scene : { content : [ Circle {centerX: 50 centerY: 50 radius: 50 fill: Color.RED } ] } } Stage Scene content Circle Stage class defines the container window, size and titleScene class defines the content to be displayed in the window 26. Example of JavaFX Application import javafx.scene.Scene; import javafx.scene.shape.Circle; import javafx.stage.Stage; Stage { scene: { content: [ Circle {centerX: 50 centerY: 50 radius: 50 fill: Color.RED } ] } } 27. Demo: http://www.javapassion.com/handsonlabs/javafx_lang/#Exercise_1 28. JavaFX Technology Stack Java2D java.awt.* SceneGraph com.sun.scenario.scenegraph.* com.sun.scenario.animation.* com.sun.scenario.effects.* JavaFX Script Programming Language javafx.gui.* javafx.gui.effect.*javafx.animation.*Java APIs script Swing javax.swing.* Note: JavaFX Script programs can call any Java APIs 29. (Some) Language Features 30. Declarations

  • Variables

31. Constantsvar fred:Number; def PI:Number = 22 / 7; Data Types

    • If not specified => compiler infers the correct type
  • var s =Hello World ;

32. var i = 10;

    • Garden variety type
      • String
    • 33. Number / Integer byte, short, int, long, BigInteger
  • 34. Boolean

35. Void 36. Data Types

  • Durations 1ms ,2s ,4m ,8h

A function can be a variable var doExit = function():Void { System.exit(0); }; doExit();//executed when invoked Functions 37. Declaring Classes // This class extends a Java interface public class FooModel extends TableModel { ... } // This class defines two variables and a function public class Location { public var x:Number; public var y:Number; public function move(newX:Number, newY:Number):Void { x = newX; y = newY; } } 38. Basic JavaFXScript Class class HelloWorldNodeextendsCustomNode { publicvartext:String; publicoverridefunctioncreate() : Node { return Text { x: 10 ,y: 50 font: Font { size: 50 } content: bind text } }; } Syntax is Java-like with shades of JavaScript 39. Object Literal class Point {var x : Integer;var y : Integer;function show() { println("Point {x}, {y}") }} //instance of object literal var myPoint = Point {x: 12,y: 9} def yourPoint = Point {x: 22,y: 19} myPoint.show()

  • declarative syntax for object creation

40. Similar to JavaScript 41. variable: initial-value 42. Sequences

  • Insert, delete

var time:Duration []= [60ms, 60s, 60m, 60h]; var days = [ 1..31 ]; insert5sintotime; delete31fromdays; A Sequence represents an ordered list of objects 43. Data Binding

  • ties the value of a variable to the value of an expression
  • Changes to thebound expressionwill cause the value to be reapplied to thefield

varh= 10; varw= 2; //Wheneverhorwchanges,areaupdated vararea=bind h * w ; println( area );//prints 20 w =3; println( area );//prints 30 Eliminates the listener pattern Useful for binding Model to View 44. Triggers

  • Associate ablock of codeto avariable

45. When the value of thevariable changes , thecode is executed 46. Similar toPropertyChangeListener //oldValue is optional vartext on replaceoldValue{ println(Old value = '{oldValue}'); println(New value = '{text}'); } text= Hello //printsOld value = '' //printsNew value = 'Hello' 47. Graphical Objects * * The fun stuff 48. JavaFX Stage SceneStageis thetop level container window Sceneis a drawing surfacecontainer that holds the scene graph nodes. content holds JavaFX graphical elements which define the graphical content of the application. 49. JavaFX Scene Graph Programming Model (cont.) top level container window container that holds the scene graph nodes 50. What is a Scene Graph?

  • A hierarchical representation ofgraphical objects
  • Tree like structure

51. Basis of JavaFX graphics engine Scene graph elements

  • Nodes - leaf:
  • images, text, shapes, custom...

Group Node Container Nodes have:

  • State visibility, opacity, transformation

52. Events mouse, keyboard, node updates 53. Animation varying properties over time 54. Group Node ContainerGroup { transforms: Translate { x:15, y, 15 } content: [ Text { x: 10, y: 50 font: Font: { size: 50 } content: Hello World } Circle { centerX: 100, centerY: 100 radius: 40 fill: Color.BLACK } ] } Group Circle Text x:15 y:15 55. JavaFX ArchitectureModels a JavaFX application Java 2D Effects Project Scene Graph 56. Base Graphical Objects

  • Graphical objects
  • Text, geometric shapes, text, Swing components

Some common attributes in nodes

  • Transformation translate, shear, rotate, scale

57. Clip displaying only part of the node based on a geometric shape 58. Effect type of effect, eg. blurring, shadowing, to apply 59. Events mouse, keyboard 60. Opacity setting the translucency 61. List is not exhaustive 62. Text

  • Defines a node for displaying text

Text { effect: DropShadow { offsetX: -10 offsetY: -10 } font: Font { name: DirtyBakersDozen size: 50 } fill: Color.ROYALBLUE stroke: Color.BLUE, strokeWidth: 3 x: 15, y: 80 content: "Hello World" } 63. Geometric Shapes

  • Arc, ellipse, line, polygon, circle, rectangle

64. Very similar to text Circle { centerX: 70, centerY: 70 radius: 50 fill: Color.PINK stroke: Color.RED strokeWidth: 3 strokeDashArray: [ 7 ] strokeDashOffset: 2 } 65. Custom Shapes

  • Two ways of defining custom shapes
  • Combining existing shapes

66. Drawing a totally new shape Combine existing shape withShapeIntersectorShapeSubtract

  • Eitheradd orsubtractfrom shape

67. Example ShapeIntersectvarrectangle=Rectangle{ x:10 y:20 width:140 height:70fill:Color.LIGHTBLUE stroke:Color.BLUE arcHeight:20 arcWidth:20 strokeWidth:3} vardiamond=Polygon { points:[90,90, 110,70, 130,90, 110,110 ]fill:Color.LIGHTPINKstroke:Color.RED strokeWidth: 3} varnewShape=ShapeIntersect{ translateX:170 fill: Color.LIGHTGREEN stroke: Color.GREEN strokeWidth: 3 //Union of the 2 shapes a: [ rectanglediamond] } 68. Custom Shapes

  • Two ways of defining custom shapes
  • Combining existing shapes

69. Drawing a totally new shape Draw new shapes withPathand path elements

  • Path elements includeMoveTo ,ArcTo ,HLine ,VLine ,QuadCurve , etc.

Can be manipulated like a regular geometric shape 70. Example Path Path { fill: Color.LIGHTGRAY stroke: Color.GRAY strokeWidth: 3 elements: [ MoveTo { x: 15 y: 15 }, ArcTo { x: 50 y: 10 radiusX: 20radiusY: 20 sweepFlag: true}, ArcTo { x: 70 y: 20 radiusX: 20radiusY: 20 sweepFlag: true}, ArcTo { x: 50 y: 60 radiusX: 20radiusY: 20 sweepFlag: true}, ArcTo { x: 20 y: 50 radiusX: 10radiusY: 5 sweepFlag:false }, ArcTo { x: 15 y: 15 radiusX: 10radiusY: 10 sweepFlag: true}, ] effect: Lighting{light: DistantLight{azimuth: 90}} } 71. Images

  • ImageView node shows images

72. Image represents an in memory Image

  • Both ImageView and Image can scale
  • Preserve ratio

73. Fit within a specific width/height 74. When fit on Image level, keeps smaller image in memory myImageView = ImageView { image: Image { url: "file:///..."} } 75. Images ImageView = ImageView { clip: Rectangle { y: 30 x: 50 width: 350 height: 100 } image: Image { url: "file:///..."} } 76. JavaFX Catalog client 77. JavaFX Stage Scene // Application User Interface var stageContent: Node[]; stageContent = [bgImage,nextButton, backButton,titleText,thumbImageViewGroup,fullImageView ]; defstage=Stage{ title: "Pet Catalog" width: 201 height: 201 scene : Scene { content : Group { content: bind stageContent } fill: Color.TRANSPARENT } } 78. JavaFX Stage Scenevar stageContent: Node[]; stageContent= [bgImage,nextButton, backButton,titleText,thumbImageViewGroup,fullImageView ]; defstage=Stage{ title: "Pet Catalog" width: 201 height: 201 scene : Scene { content : Group { content: bindstageContent } fill: Color.TRANSPARENT } } 79. Effects

  • Effects are placed on Nodes

80. Many standard built in

    • DropShadow
  • 81. ColorAdjust

82. GaussianBlur 83. Glow 84. Reflection 85. more... 86. Example: DropShadowText { effect: DropShadow{ offsetY: 3 color:Color.GREEN radius: 20.0 }; ... }, Circle { effect: DropShadow{ offsetX: 10 offsetY:20 color:Color.BLUE radius: 30.0 } ... } 87. Some Effects Supported In JavaFX effect: 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 88. Lighting Effect effect: Lighting{ surfaceScale: 7 light: DistantLight{ azimuth: 90 elevation: 30 } } effect: Lighting{ surfaceScale: 7 light: SpotLight { x: 0 y :0 z: 50 pointsAtX: 10 pointsAtY: 10pointsAtZ: 0 color: Color.YELLOW } } 89. Demo: DropShadow, http://www.javapassion.com/handsonlabs/javafx_guibasics/index.html#7.1 DropShadow with Binding, http://www.javapassion.com/handsonlabs/javafx_customnode/index.html EffectsPlayground http://javafx.com/samples/EffectsPlayground/index.html 90. Interactions 91. Handling Events

  • All nodes have eithermouseor 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 thecursorattribute

92. Example Handling Events var 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; } } Changing the color of the rectangle 93. Example Handling Events var sx:Number = 0; var dx:Number = 0; var sy:Number = 0; var dy:Number = 0; var rectangle:Rectangle = Rectangle { x:binddx y:binddy width: 150 height: 70 arcWidth: 50, arcHeight: 50 fill: Color.LIGHTBLUE stroke: Color.ROYALBLUE strokeWidth: 3 cursor : Cursor.HAND onMousePressed :function( e: MouseEvent ) :Void { sx = e.dragX - dx; sy = e.dragY - dy; } onMouseDragged :function( e: MouseEvent ) :Void { dx = e.dragX - sx; dy = e.dragY - sy; } } Dragging an object around the screen 94. Demo: Simple Sketch gui2_interaction_Sketch_basic_3steps http://www.javapassion.com/handsonlabs/javafx_guibasics2/#1.3 95. Two Types of Animation in JavaFX

  • Transition
    • Precanned animation
  • 96. Single purpose
  • Animation
    • More flexible but more code

97. Transitions

  • Predefined animations to perform a specific task
  • Position, rotation, opacity, etc.

98. Need to specify the node to perform the transition on 99. geometric shapes, images, text, Swing components Out of the box transitions

  • RotateTranstion rotation

100. FadeTransition opacity 101. TranslateTransition move a node along a straight line 102. PathTransition move an object along a defined path 103. ScaleTranstion grows or shrinks a node 104. RotationTransition var rNode= Rectangle {....} var rotTransition = RotateTransition { duration: 3s node:rNode byAngle: 180 repeatCount:4 autoReverse: true } var princess:ImageView = ImageView { image: Image { url: "{__DIR__}princess.png" } onMouseClicked: function( e: MouseEvent ):Void { rotTransition.play(); } } 105. Demo: Transitions http://www.javapassion.com/handsonlabs/javafx_animation/#Exercise_1 http://www.javapassion.com/handsonlabs/javafx_animation/#Exercise_2 106. Programming Model for Key Frame Animation

  • Animation occurs along a timeline, represented by aTimelineobject.

var tRadius =Timeline{ keyFrames: [ KeyFrame{ time: 0ms values:}, KeyFrame{ time: 500ms values:} ] }; Animated state transitions of each "scene" are declared as "snapshots" ( KeyFrame s ) of state at certain points in time. "snapshots" of state at certain time 107. Animation

  • Define severalKeyFrame s ( snapshots of state ) at different time intervals

108. Assign theseKeyFrame s toTimeline

  • Playback control

timeline.playFromStart() timeline.rate = -1 //Play in reverse, normal speed 109. Demo: simple animation http://www.javapassion.com/handsonlabs/javafx_animation/ 110. Example expanding Circle varcRadius; var circle: Circle = Circle { centerX: 300, centerY: 300 radius: bindcRadius fill: Color.LIGHTBLUE onMousePressed: function( e: MouseEvent ):Void { tRadius.playFromStart(); } } Stage { scene: Scene { content: [circle] } } 111. Example Defining Key Frames vartRadius : Timeline = Timeline { keyFrames: [ KeyFrame {//start point time: 0s values: [cRadius =>30 ] } KeyFrame {//end point time: 5s values: [ cRadius =>300tweenInter polator.LINEAR ] } ] } movement from the beginning to the end states Interpolator calculatesthe states that occur betweenanimation frames 0s 1s 2s 3s 4s 5s 6s Key value radius = 30 radius = 300 Keyframes How the value changes over time 112. at()(Shorthand notation) keyFrames: [ at(0ms) { cRadius => 30 } at(500ms) { cRadius => 300 tween Interpolate.LINEAR } ] vartRadius= Timeline { keyFrames: [ KeyFrame { time: 0ms values: [cRadius => 30 ] }, KeyFrame { time: 500ms values: [cRadius => 300 tween Interpolator.LINEAR ] } ] }; 113. Example expanding Circle varcRadius:Number = 30; vartRadius :Timeline = Timeline { keyFrames: [ at(3s) { cRadius=> 200 tween Interpolator.LINEAR} ] }; var circle: Circle = Circle { centerX: 300, centerY: 300 radius: bindcRadius fill: Color.LIGHTBLUE onMousePressed: function( e: MouseEvent ):Void { tRadius.playFromStart(); } } 114. Example Animating an Object varx : Number=0; Timeline { keyFrames: [ at (7s) { x=> 387.0 tween Interpolator.LINEAR} ] }.play(); Path{ ... translateX: bindx ...} 115. Demo: Building Picture Display Step by Step http://www.javapassion.com/handsonlabs/javafx_customnode/index.html 116. Work with Restful Web Services 117. RESTful Catalog Service JavaFX clientJAX-RS, JAXB, JPA DB Registration Application JAX-RS class JavaFXclient JAXB class Entity Class ItemsConverter Item ItemsResource 118. Article on SDN 119. RESTful Pet Catalog Web Servicehttp://petstore/catalog/resources/items/ HTTPGET Response XML items http://host/catalog/images/anthony.jpgFriendly Cat307.10feline01Server ClientAddressable Resources Web Container 120. Accessing REST Resources

  • Includes an asynchronous HTTP request class

121. Need to specify the location and the HTTP method 122. Provides callback functions

  • onInput(), onDone()

Invokeenqueue()to start request 123. JavaFXHttpRequest function loadImageMetadata() { var start=page * 9;var request: HttpRequest = HttpRequest { location:" http://localhost:8080/catalog/resources/items/ " method: HttpRequest.GET onInput:function(input: java.io.InputStream) {var parser = PhotoPullParser{}; photos =parser.parse(input) ;} onDone:function() { updateImages() ; } } request.enqueue(); } Performs HTTP GET on urlcatalog/items 124. javafx.data.pull.PullParser

  • parser that supports JSON and XML

125. To use in 'event' mode def parser = PullParser {documentType: PullParser.XML;input: anInputStreamThatContainsXML; onEvent: function(event: Event) { if (event.type == PullParser.START_ELEMENT) { . . . } } } parser.parse();

  • Can be used in 'linear' mode as well

126. Direct the parser withparser.forward()andparser.seek( QName{name:"child"} ) 127. JavaFXParser public class PhotoPullParser { public function parse(input: InputStream): Photo[] { varphotos: Photo[]; var photo: Photo; def parser = PullParser { input: input onEvent:function(event: Event) { if (event.type ==PullParser.START_ELEMENT ) { if(event.qname.name == "item" and event.level == 1) { photo = Photo { }; } } else if (event.type ==PullParser.END_ELEMENT ) { if( event.qname.name == " item "and event.level == 1) { insert photo into photos; } else if( event.qname.name == " imagethumburl "and event.level == 2){ photo.imagethumburl = event.text; }... } } } parser.parse(); return photos; } http://y.jpgFriendly Cat ... 128. Media 129. Motivation and Goals

  • Video and audio are ubiquitous on the Net

130. Top grade media support

  • Simple

131. Zero configuration, 132. support whatever the native platform (Windows, Mac, ) supports 133. Integration with JavaFXscenegraph 134. Example of Creating a Media Player varvideo :Media =Media{ source: "http://..." }; varplayer :MediaPlayer =MediaPlayer{ media:video rate: 1.0 volume: 0.4 }; varview :MediaView =MediaView{ mediaPlayer:player x:200 y:200 }; Stage { title: "Media Player" width: 700 height: 700 scene: Scene { content: [view] } } controls for playing media Display for MediaPlayer Media source 135. Demo: Media 136. Deployment 137. Deployment Options

  • JavaFX 1.0 applications can be deployed using:
  • JavaPlugin : as Javaapplets
  • web browser

JavaWeb Start :stand-alone Java applications

  • desktop, using JNLP (Java Network Launching Protocol).

Applets can be dragged and dropped to desktop Or using mobile emulation

  • JavaFX 1.0 Mobile Emulator: displays applications as they would look on a typical mobile device.

138. Carol McDonald Technology Evangelist [email_address]