Java Fx Overview Tech Tour

  • 1,560 views
Uploaded on

JavaFX overview

JavaFX overview

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads

Views

Total Views
1,560
On Slideshare
0
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
20
Comments
0
Likes
0

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide
  • escribe and present your product(s)/product line/service(s), technology, solution at a mid to high-level. Avoid low-level technical details (reserve to Systems Engineering training if needed) What are the business/technology value propositions? What is your BU vision and strategy? What OEM specific programs / resources do you have? How does your product/solution fit into an overall Sun open source /solution/story? JavaFX is the, Java-based, rich client platform for building RIA applications and content across multiple platforms Messages Designed to enable consistent user experiences, from desktop to mobile device to set-top box to Blu-ray Disc _________________________________________________ Zoom in on the FX portion of the Markecture diagram with a cool visual effect As Rich talks about a portion of Java FX, the component name is the only thing on the screen, high contrast, big font If there are cool visuals for the component, sprinkle them in
  • Now here it is in JavaFX Script: Notice how both the frame's stage and the circle class use the same name for the background: fill. And if you want to get rid of the window's background you just set fill to null. It's consistent and easy. *that's* the value of creating a new API.
  • The public-read Access Modifier The public-read access modifier defines a variable that is publicly readable, but (by default) is writeable only from within the current script. To widen its write access, prepend either the package or protected modifier (i.e. package public-read or protected public-read). Doing so will set its write access to the package or protected level. The public-init Access Modifier The public-init access modifier defines a variable that can be publicly initialized by object literals in any package. Subsequent write access, however, is controlled in the same manner as public-read (the default is write access at the script-level, but prepending package or protected will widen the access accordingly). The value of this variable is always readable from any package.
  • Function An executable body of code that performs a particular task Function does not execute until it is invoked There are two levels of function: script level and object level Function can be a variable
  • Classes extend classes or interfaces Scope modifiers: public, protected, package Implicitly “script private” init { } and postinit { } blocks take place of Constructors Functions and variables declared outside a class are static Multiple classes may be defined in a single Script
  • Classes extend classes or interfaces Scope modifiers: public, protected, package Implicitly “script private” init { } and postinit { } blocks take place of Constructors Functions and variables declared outside a class are static Multiple classes may be defined in a single Script
  • A Sequence represents an ordered list of objects; the objects of a sequence are called items. JavaFX has “Sequences”, not arrays A Sequence is an immutable ordered list of non-null elements JavaFX supports sequence comprehensions Sequences can be “sliced” Sequences can optimize memory usage
  • bind is a way to tie the value of one variable to the value of an expression binding must be defined when the variable is initialized bindings are statically compiled bound variables cannot be set manually use bind with inverse for bidirectional binding
  • The MoveTo class indicates the start point for the shape, and the ArcTo class creates an arc segment. All segments are combined into a shape using the Path class which represents a simple shape, and enables basic construction of a geometric path. The Path class is helpful when you need to create your own shape that is different from the primitive graphic shapes available in the javafx.scene.shape package. The Path class extends the Node class and inherits all of its instance variables and functions. Note: The sweepFlag instance variable is set to true so that the arc be drawn clockwise, in a "positive" angle. If the arcs are drawn counterclockwise, they will not curve correctly.
  • The movement from the beginning to the end states, commonly called "tweening," is specified with the tween operator. The Interpolator.LINEAR value means that movement will progress at a steady rate from the beginning position to the end position.

Transcript

  • 1. JavaFX - Rich GUIs Made Easy Carol McDonald Technology Evangelist
  • 2. Agenda
    • JavaFX Script Language Overview
    • 3. Advanced features
    • JavaFX Application Deployment
    • 8. Summary and References
  • 9. Overview of the JavaFX SDK
  • 10. JavaFX Vision *
    • Rich Clients
    • 11. Multiple devices
    JavaFX is THE platform for creating and delivering Rich Internet Application s across 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
    • The PerspectiveTransform built 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 result
    println(“ 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 title Scene 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 var 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 HelloWorldNode extends CustomNode { public var text:String; public override function create() : 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 ]; insert 5s into time; delete 31 from days; 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 the bound expression will cause the value to be reapplied to the field
    var h = 10; var w = 2; //Whenever h or w changes, area updated var area = 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 a block of code to a variable
    • 45. When the value of the variable changes , the code is executed
    • 46. Similar to PropertyChangeListener
    //oldValue is optional var text on replace oldValue { println(“Old value = '{oldValue}'”); println(“New value = '{text}'”); } text = “Hello” //prints Old value = '' //prints New value = 'Hello'
  • 47. Graphical Objects * * The fun stuff
  • 48. JavaFX Stage Scene Stage is the top level container window Scene is a drawing surface container 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 of graphical 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 Container Group { 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 Architecture Models 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 with ShapeIntersect or ShapeSubtract
      • Either add or subtract from shape
  • 67. Example – ShapeIntersect var rectangle = Rectangle { x:10 y:20 width:140 height:70 fill:Color.LIGHTBLUE stroke:Color.BLUE arcHeight:20 arcWidth:20 strokeWidth:3} var diamond = Polygon { points:[90,90, 110,70, 130,90, 110,110 ] fill:Color.LIGHTPINK stroke:Color.RED strokeWidth: 3} var newShape = ShapeIntersect { translateX:170 fill: Color.LIGHTGREEN stroke: Color.GREEN strokeWidth: 3 //Union of the 2 shapes a: [ rectangle diamond ] }
  • 68. Custom Shapes
    • Two ways of defining custom shapes
      • Combining existing shapes
      • 69. Drawing a totally new 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
  • 70. Example – Path Path { fill: Color.LIGHTGRAY stroke: Color.GRAY strokeWidth: 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}, ] 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 ]; def stage = Stage { title: "Pet Catalog" width: 201 height: 201 scene : Scene { content : Group { content: bind stageContent } fill: Color.TRANSPARENT } }
  • 78. JavaFX Stage Scene var stageContent: Node[]; stageContent = [bgImage, nextButton, backButton, titleText, thumbImageViewGroup, fullImageView ]; def stage = Stage { title: "Pet Catalog" width: 201 height: 201 scene : Scene { content : Group { content: bind stageContent } fill: Color.TRANSPARENT } }
  • 79. Effects
    • Effects are placed on Nodes
    • 80. Many standard built in
  • 86. 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 } ... }
  • 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: 10 pointsAtZ: 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 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
  • 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: bind dx y: bind dy 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 a Timeline object.
    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 several KeyFrame s ( snapshots of state ) at different time intervals
    • 108. Assign these KeyFrame s to Timeline
    • 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 var cRadius; var circle: Circle = Circle { centerX: 300, centerY: 300 radius: bind cRadius fill: Color.LIGHTBLUE onMousePressed: function( e: MouseEvent ):Void { tRadius.playFromStart(); } } Stage { scene: Scene { content: [circle] } }
  • 111. Example – Defining Key Frames var tRadius : Timeline = Timeline { keyFrames: [ KeyFrame { //start point time: 0s values: [ cRadius => 30 ] } KeyFrame { //end point time: 5s values: [ cRadius => 300 tween Inter polator.LINEAR ] } ] } movement from the beginning to the end states Interpolator calculates the states that occur between animation 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 } ] var tRadius = Timeline { keyFrames: [ KeyFrame { time: 0ms values: [cRadius => 30 ] }, KeyFrame { time: 500ms values: [ cRadius => 300 tween Interpolator.LINEAR ] } ] };
  • 113. Example – expanding Circle var cRadius:Number = 30; var tRadius :Timeline = Timeline { keyFrames: [ at(3s) { cRadius => 200 tween Interpolator.LINEAR} ] }; var circle: Circle = Circle { centerX: 300, centerY: 300 radius: bind cRadius fill: Color.LIGHTBLUE onMousePressed: function( e: MouseEvent ):Void { tRadius.playFromStart(); } }
  • 114. Example – Animating an Object var x : Number=0; Timeline { keyFrames: [ at (7s) { x => 387.0 tween Interpolator.LINEAR} ] }.play(); Path{ ... translateX: bind x ...}
  • 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 client JAX-RS, JAXB, JPA DB Registration Application JAX-RS class JavaFX client JAXB class Entity Class ItemsConverter Item ItemsResource
  • 118. Article on SDN
  • 119. RESTful Pet Catalog Web Service http://petstore/catalog/resources/items/ HTTP GET Response XML items <item> <imageurl>http://host/catalog/images/anthony.jpg</imageurl> <name>Friendly Cat</name> <price>307.10</price> <productid>feline01</productid> </item> Server Client Addressable 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()
    • Invoke enqueue() to start request
  • 123. JavaFX HttpRequest function loadImageMetadata() { var start=page * 9; var request: HttpRequest = HttpRequest { location: &quot; http://localhost:8080/catalog/resources/items/ &quot; 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 url catalog/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 with parser.forward() and parser.seek( QName{name:&quot;child&quot;} )
  • 127. JavaFX Parser public class PhotoPullParser { public function parse(input: InputStream): Photo[] { var photos: Photo[]; var photo: Photo; def parser = PullParser { input: input onEvent: function(event: Event) { if (event.type == PullParser.START_ELEMENT ) { if(event.qname.name == &quot;item&quot; and event.level == 1) { photo = Photo { }; } } else if (event.type == PullParser.END_ELEMENT ) { if( event.qname.name == &quot; item &quot; and event.level == 1) { insert photo into photos; } else if( event.qname.name == &quot; imagethumburl &quot; and event.level == 2){ photo.imagethumburl = event.text; } ... } } } parser.parse(); return photos; } <item> <imageurl>http://y.jpg</imageurl> <name>Friendly Cat</name> ... </item>
  • 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 JavaFX scenegraph
  • 134. Example of Creating a Media Player var video :Media = Media { source: &quot;http://...&quot; }; var player :MediaPlayer = MediaPlayer { media: video rate: 1.0 volume: 0.4 }; var view :MediaView = MediaView { mediaPlayer: player x:200 y:200 }; Stage { title: &quot;Media Player&quot; 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:
      • Java Plugin : as Java applets
        • web browser
      • Java Web 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]