Your SlideShare is downloading. ×
0
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Java Fx
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Java Fx

4,730

Published on

Presentation on Java FX

Presentation on Java FX

Published in: Technology, Education
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
4,730
On Slideshare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
116
Comments
0
Likes
1
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

Transcript

  • 1. JavaFX Workshop 1
  • 2. What is & Why JavaFX?
  • 3. 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
  • 4. What does RIA mean today? Extend RIA, across multiple screens
  • 5. 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
  • 6. Key Features of JavaFX
  • 7. 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.
  • 8. 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.
  • 9. Things You Can Build with JavaFX
  • 10. 3-D Display Shelf With the PerspectiveTransform • The PerspectiveTransform built into JavaFX can be used to easily create 3-D effects
  • 11. 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.
  • 12. 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.
  • 13. 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
  • 14. JavaFX Platform Architecture
  • 15. JavaFX Platform Architecture
  • 16. Example: Hello World in JavaFX Declarative Syntax Stage { title: "Welcome to JavaFX!" scene: Scene { content: [ Text { content: "Hello World!" x:25 y:25 fill: Color.BLACK font: Font{ size: 32 } } ] } }
  • 17. Data Types
  • 18. Basic Data Types • Boolean • Integer • Number • String • Duration Data types cannot be null
  • 19. 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.
  • 20. 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'
  • 21. 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 two println(three); // 'This example joins two strings.'
  • 22. 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.
  • 23. Boolean • The Boolean type represents two values: true or false var isAsleep = true; • or when evaluating a conditional expression: if (isAsleep) { wakeUp(); }
  • 24. Duration • The Duration type represents a fixed unit of time (millisecond, second, minute, or hour.) 5ms; // 5 milliseconds 10s; // 10 seconds 30m; // 30 minutes 1h; // 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
  • 25. Void • Void is used to indicate that a function does not return any value: • The following two are equivalent // Return type is set to Void function printMe() : Void { println("I don't return anything!"); } // No return type function printMe() { println("I don't return anything!"); }
  • 26. 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."); } }
  • 27. Script Variables
  • 28. 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;
  • 29. 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.
  • 30. Writing Your Own Classes
  • 31. Class Definition • Address class definition: The Address class declares street, city, state, and zip instance variables all of type String class Address { var street: String; var city: String; var state: String; var zip: String; }
  • 32. Class Definition • Customer class definition with functions - functions are like methods in Java class Customer { var firstName: String; var lastName: String; var phoneNum: String; var address: Address; function printName() { println("Name: {firstName} {lastName}"); } function printPhoneNum(){ println("Phone: {phoneNum}"); }
  • 33. Object Literals
  • 34. 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.)
  • 35. 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
  • 36. 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 initialization Rectangle { x: 10 y: 10 width: 100 height: 100 }
  • 37. Declaring Object Literals • When declaring an object literal, the instance variables may be separated by commas or whitespace, as well as the semi-colon Address { 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 }
  • 38. 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 } }
  • 39. 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 }
  • 40. Sequences
  • 41. 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.
  • 42. 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
  • 43. 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).
  • 44. 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"];
  • 45. 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];
  • 46. 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.
  • 47. 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 Mon println(days[1]); // prints Tue println(days[2]); println(days[3]); println(days[4]); println(days[5]);
  • 48. 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);
  • 49. 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 point insert "Tue" into days; insert "Fri" into days; insert "Sat" into days; insert "Sun" into days; // The sequence contains: "Mon", "Tue", "Fri", "Sat", and "Sun".
  • 50. 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".
  • 51. Deleting Items from a Sequence • The delete and from keywords make it easy to delete items from a sequence delete "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;
  • 52. 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]
  • 53. 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
  • 54. 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];
  • 55. 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..<];
  • 56. Functions
  • 57. 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}");
  • 58. 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}"); }
  • 59. Returning Values from Functions • A function may also return a value to the code that invokes it function add(argOne: Integer, argTwo: Integer) : Integer { result = argOne + argTwo; println("{argOne} + {argTwo} = {result}"); return result; }
  • 60. Operators
  • 61. 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.
  • 62. 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"];
  • 63. 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
  • 64. 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 10 println(result); result /= 2; // result is now 5 println(result);
  • 65. 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 0 println(result); result++; // result is now 1 println(result); result = -result; // result is now -1 println(result); var success = false; println(success); // false println(not success); // true
  • 66. 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
  • 67. Expressions
  • 68. 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.
  • 69. Types of Expression • Block expression • if expression • Range expression • for expression • while expression • break and continue expression • throw, try, catch, and finally expression
  • 70. 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.
  • 71. 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.
  • 72. if Expression • if (booleanExpression) then a else b • if (booleanExpression) a else b • if (booleanExpression) { a } else { b }
  • 73. for Expression • for (i in sequence) { ... }
  • 74. 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 interval var nums = [1..10 step 2]; // [ 1, 3, 5, 7, 9 ] println(nums); // descending range var nums = [10..1 step -1]; // [ 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 ] println(nums);
  • 75. Access Modifiers
  • 76. 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
  • 77. JavaFX GUI Basics 1
  • 78. Quick JavaFX GUI Overview
  • 79. User Interface Elements • Standard UI components you can create using the javafx.ext.swing package.
  • 80. Colors • Color patterns for all constants of the javafx.scene.paint.Color class
  • 81. Shapes and Fill Styles • javafx.scene.shape and javafx.scene.paint packages
  • 82. Text • Different formatting styles applied to the same text string
  • 83. Effects • Effects can be applied to the JavaFX UI elements
  • 84. Transformation • Transformations can be performed for the graphics, images, or text
  • 85. Layout • There are several methods of laying out UI elements using the javafx.scene.layout package. • •
  • 86. Cursors • Different views of cursor you can apply to any UI element
  • 87. Using Declarative Syntax (for Creating GUI)
  • 88. 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.
  • 89. Step by Step Process of Creating a Simple GUI
  • 90. 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
  • 91. Step by Step Process of Creating a GUI 1.Add necessary imports 2.Create an Application window 3.Set the Scene 4.Create a Rectangle 5.Create a Circle 6.Change the code (so that the Circle gets underneath the Rectangle)
  • 92. 1. Add Necessary Imports import javafx.stage.Stage; // required to render a window import javafx.scene.Scene; // required to display a circle and // rectangle on a window import javafx.scene.shape.Rectangle; // required to render the rectangle import javafx.scene.paint.Color; // required to fill and stroke the // rectangle and circle with color import javafx.scene.shape.Circle; // required to render the circle
  • 93. 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 }
  • 94. 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.
  • 95. 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: [ ] } }
  • 96. 4. Create a Rectangle Stage { ... 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 } ] }
  • 97. 5. Create a Circle Stage { ... 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 } ] }
  • 98. 6. Place Circle Underneath Rectangle Stage { ... scene: Scene { content: [ // Place the circle underneath the square. To do so, switch the order // of the circle and square Circle{ .... }, Rectangle { ... } ] } }
  • 99. JavaFX Application Structure
  • 100. 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
  • 101. Example: Stage Stage { title: "Welcome to JavaFX!" scene: Scene { content: [ Text { content: "Hello World!" x:25 y:25 fill: Color.BLACK font: Font{ size: 32 } } ] } }
  • 102. 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
  • 103. Scene Graph
  • 104. 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.
  • 105. JavaFX Architecture JavaFX Script Software Models a GUI Project Scene Graph part of a JavaFX Effects application Java 2D Graphics hardware
  • 106. 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
  • 107. 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
  • 108. Scene Graph: Group • Group stands a set of Nodes which may have same effect • Group itself is a Node, so can be nested
  • 109. Scene Graph: Group Group { transforms: Translate { Gro up x:15, y, 15 } x content: [ : Text { 1 x: 10, y: 50 5 y: font: Font: { 1 size: 50 5 } content: “Hello World” } Circle { Text Circle centerX: 100, centerY: 100 radius: 40 fill: Color.BLACK } ] }
  • 110. Shapes
  • 111. Shapes • Arc • Rectangle • Circle • stroke • Ellipse • strokeWidth • Line • fill • Path • smooth • Polygon
  • 112. Geometric Shapes • Arc, ellipse, line, polygon, circle, rectangle • Very similar to text Circle { centerX: 70, centerY: 70 radius: 50 fill: Color.PINK stroke: Color.RED strokeWidth: 3 strokeDashArray: [ 7 ] strokeDashOffset: 2 }
  • 113. 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
  • 114. Example – ShapeIntersect ShapeIntersect { transforms: [ Translate { x: 170 } ] fill: Color.LIGHTGREEN stroke: Color.GREEN strokeWidth: 3 //Union of the 2 shapes a: [rectangle diamond ] }
  • 115. 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}, ] }
  • 116. Other Graphical Objects
  • 117. 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
  • 118. 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" }
  • 119. 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
  • 120. Images ImageView = ImageView { clip: Rectangle { y: 30 x: 50 width: 350 height: 100 } image: Image { url: "..."} }
  • 121. 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
  • 122. Effects
  • 123. 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
  • 124. 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.
  • 125. Effects: DropShadow
  • 126. 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
  • 127. Example: DropShadow Text { effect: DropShadow { offsetY: 3 color: Color.color(0.4, 0.4, 0.4) }; ... }, Circle { effect: DropShadow { offsetY: 4 }, ... }
  • 128. 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 }
  • 129. Effects: Lighting
  • 130. 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 } }
  • 131. Effects: PerspectiveTransform
  • 132. 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); }, ]
  • 133. Effects: Linear Gradients
  • 134. 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
  • 135. Effects: Glow, Reflection, GaussianBlur
  • 136. Some Effects Supported In JavaFX effect: SepiaTone { level: 0.5 } effect: Glow { level: 0.7 } Original image effect: GaussianBlur { input: SepiaTone { level: 0.5 } radius: 10.0 } effect: Reflection { fraction: 0.7 }
  • 137. JavaFX Script Language: Data binding & Triggers 1
  • 138. What is Binding?
  • 139. 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.
  • 140. 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
  • 141. 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.
  • 142. Binding to a Variable of Basic Type
  • 143. Binding to a Basic Type var 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 object def y = bind x; x = 1; println(y); // y now equals 1 x = 47; // Because the variables are bound, the value of y // automatically updates to the new value. println(y); // y now equals 47
  • 144. Binding to an Object
  • 145. Binding to an Object var 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”
  • 146. Binding to an Object var 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”
  • 147. Binding to a Function
  • 148. 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
  • 149. Definition of a Bound Function var 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; }
  • 150. 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
  • 151. Transformation
  • 152. Transformation class • Provides functions to perform > rotating > scaling > shearing > translation
  • 153. Rotate Transformation • Rotates coordinates around an anchor point Stage { title: "Welcome to JavaFX!" scene: Scene { width: 200 height: 200 content: [ Rectangle { transforms: Rotate { angle: bind angle pivotX: 10 pivotY: 10 } ... } ] } }
  • 154. Scale Transformation • Scales coordinates by the specified factors Stage { 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
  • 155. Shear Transformation • Shears coordinates by the specified multipliers Stage { 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; } } ] } }
  • 156. Translation Transformation • Translates coordinates by the specified factors Stage { 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; } } ]
  • 157. Interactions
  • 158. 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
  • 159. Example: Handling Events • Mouse events change the color of an rectangle 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; } }
  • 160. Drag and Drop
  • 161. Drag and Drop (using sceneX, sceneY) • Drag an object around the screen var 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; } }

×