SlideShare a Scribd company logo
1 of 161
Download to read offline
JavaFX Workshop




                  1
What is & Why JavaFX?
Rich Clients Are Changing the Game!
• Clients are becoming visually rich
  > Too much engineering effort to create using traditional tools
  > Challenging the conventional notion of GUI toolkits
     > Buttons with image → Image buttons (HTML) → ???

• Clients are omnipresence
  > The concept of one software on one computer is dying...
  > Browsers are no longer the only client - They are used as
    delivery vehicles
• Clients are designed rather than programmed
  > Working together with graphic designers to conceptualize the
    interface and use cases
What does RIA mean today?




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




       JavaFX is Powered by Java
Key Features of
JavaFX
Key Features
• One-stop shop RIA platform for all screens:
  > Build engaging visual experiences across desktop, browser
    and mobile with a unified development and deployment
    model.
• Broadest market reach:
  > Distribute RIAs easily across billions of devices with the
    power of Java.
• Designer-developer workflow:
  > Dramatically shorten your production cycle for design and
    development.
Key Features (Continued)
• Break free from the browser:
  > Drag-and drop a JavaFX application from the browser to
    deploy to the desktop.
• Built over powerful Java runtime:
  > Leverage the extreme ubiquity, power, performance and
    security of the Java runtime.
• Java technology compatibility:
  > Preserve your investment by enabling the use of any Java
    library within a JavaFX application.
Things You Can Build
with JavaFX
3-D Display Shelf With the
PerspectiveTransform
• The PerspectiveTransform built into JavaFX can be
  used to easily create 3-D effects
Flying Saucer
• The new out-of-process Java applet plugin in Java SE 6
  update 10 enables you to make applets which can run
  outside of the browser.
Simple Video Player
• Incorporating video in your application is as simple as
  creating an instance of this component, setting a few
  variables and including a link to your video source.
VideoCube
• Shows how to use JavaFX technology to rotate a cube
  that displays video on its faces. The sample enables
  the user to click a cube face to play video, or drag a
  face to rotate the cube
JavaFX Platform
Architecture
JavaFX Platform Architecture
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
                 }
            }
        ]
    }
}
Data Types
Basic Data Types
•   Boolean
•   Integer
•   Number
•   String
•   Duration

Data types cannot be null
String: Declaration
• A String can be declared using either single or double
  quotes:
  > var s1 = 'Hello';
  > var s2 = "Hello";
• Single and double quotes are symmetrical: you can
  embed single quotes within double quotes, and double
  quotes within single quotes.
• There is no difference between single- and double-
  quoted strings.
String: Embedded Expressions
• You can also embed expressions inside a string using
  curly braces "{}":
  > def name = 'Joe';
  > var s = "Hello {name}"; // s = 'Hello Joe'
• The embedded expression can itself contain quoted
  strings, which, in turn, can contain further embedded
  expressions:
  > def answer = true;
  > var s = "The answer is {if (answer) "Yes" else "No"}"; // s =
    'The answer is Yes'
String: Joining (Concatenating)
• To join (concatenate) multiple strings, use curly braces
  inside the quotes:
 def one = "This example ";
 def two = "joins two strings.";
 def three = "{one}{two}"; // join string one and string two
 println(three);              // 'This example joins two strings.'
Number and Integer: Declaration
• The Number and Integer types represent numerical data,
  although for most scripting tasks, you will usually just let the
  compiler infer the correct type:
  def numOne = 1.0; // compiler will infer Number
  def numTwo = 1; // compiler will infer Integer
• You can, however, explicitly declare a variable's type:
  def numOne : Number = 1.0;
  def numTwo : Integer = 1;
• Number represents floating-point numbers while Integer only
  represents integers.
• Use Number only when you absolutely need floating-point
  precision. In all other cases, Integer should be your first choice.
Boolean
• The Boolean type represents two values: true or false
 var isAsleep = true;
• or when evaluating a conditional expression:
 if (isAsleep) {
      wakeUp();
 }
Duration
• The Duration type represents a fixed unit of time
  (millisecond, second, minute, or hour.)
 5ms; // 5 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
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!");
 }
Null
• Null is a special value used to indicate a missing
  normal value.
• Null is not the same as zero or an empty string, so
  comparing for null is not the same as comparing for
  zero or an empty string.
 function checkArg(arg1: Address) {
    if(arg1 == null) {
        println("I received a null argument.");
    } else {
        println("The argument has a value.");
    }
 }
Script Variables
Script Variables
 • Script variables are declared using the var or def
   keywords.
    > The difference between the two is that var variables may be
       assigned new values throughout the life of the script,
       whereas def variables remain constant at their first assigned
       value.


def numOne = 100;
def numTwo = 2;
var result;
Type Inference (by Compiler)

• You don't have to explicitly specify the types of variable
  in JavaFX
• The compiler is smart enough to figure out your intent
  based on the context in which the variable is used. This
  is known as type inference.
• Type inference makes your job as a script programmer
  a little easier because it frees you from the burden of
  declaring the data types that your variable is compatible
  with.
Writing Your Own
Classes
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;
  }
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}");
   }
Object Literals
What is an Object? (Same as in Java)
• Objects represent state and behavior
  > An object's state is represented by its variables.
  > An object's behavior is represented by its functions.
• Conceptually an object can model just about anything,
  from GUI components (buttons, check boxes, text
  labels) to non-visual abstractions (temperature data,
  financial records, product registration information, etc.)
Object Literal
• In the JavaFX Script programming language, an object
  can be created with an object literal (unlike Java)
• Concise declarative syntax
• Similar to JavaScript
• Combine with binding for maximum benefit
Example: Object Literal
• The first word (Rectangle) specifies the type of object,
  class, that you are creating
  > variable: initial-value // initial-value is an expression


 // Create a Rectangle
 // x: 10 is not an assignment, it is an initialization
 Rectangle {
     x: 10 y: 10
     width: 100
     height: 100
 }
Declaring Object Literals
• When declaring an object literal, the instance variables
  may be separated by commas or whitespace, as well
  as the semi-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
 }
Nesting an Object inside Another Object
• Nesting Color object inside Rectangle object

 var rect = Rectangle {
    x: 10
    y: 10
    width: 100 height: 100
    fill: Color {
           red: 1
           green: 0
           blue: 0
    }
 }
Assigning an Object Literal to a Variable
  // A variation that allows me to reference the
 // color later
 var color:Color;
 var rect = Rectangle {
     x: 10 y: 10 width: 100 height: 100
    fill: color = Color {
       red: 1
       green: 0
       blue: 0
    }
 }
 var rect2 = Rectangle {
     x: 200 y: 10 width: 100 height: 100
     fill: color
 }
Sequences
What is a Sequence?
• In addition to the five basic data types, the JavaFX
  Script programming language also provides data
  structures known as sequences.
• A Sequence represents an ordered list of objects; the
  objects of a sequence are called items.
Creating Sequences
• One way to create a sequence is to explicitly list its
  items.
• Each element is separated by a comma and the list is
  enclosed in square brackets [ and ]
  > For example, the following code declares a sequence and
    assigns it to a variable named weekDays
     > var weekDays = ["Mon","Tue","Wed","Thu","Fri"];
  > The compiler knows that we intend to create a "sequence of
    strings" because the individual items are all declared as
    String literals
Specifying Sequence's Type Explicitly
• You can also explicitly specify a sequence's type by
  modifying its variable declaration to include the name of
  the type followed by "[]":
  > var weekDays: String[] = ["Mon","Tue","Wed","Thu","Fri"];
  > This tells the compiler that the weekDays variable will hold a
    sequence of Strings (as opposed to a single String).
Sequences Within Other Sequences
• Sequences can also be declared within other
  sequences:
 var days = [weekDays, ["Sat","Sun"]];

 // In such cases, the compiler will automatically flatten the
 // nested sequences to form a single sequence, making the
 // above equivalent to:
 var days = ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"];
Sequences with Shorthand Notation
• There is also a shorthand notation that makes it easier
  to create sequences that form an arithmetic series.
• To create a sequence consisting of the numbers 1
  through 100, use the following:
  > var nums = [1..100];
Creating Sequences with Predicate

• You can use a boolean expression, or a predicate, to
  declare a new sequence that is a subset of an existing
  sequence. For example, consider the following:
 var nums = [1,2,3,4,5];
• To create a second sequence (based on items found in this
  first sequence) but containing only numbers greater than 2,
  use the following code:
 var numsGreaterThanTwo = nums[n | n > 2];
 // Select all items from the num sequence where the value of an
 // item is greater than 2 and assign those items to a new sequence
 // called numsGreaterThanTwo.
Accessing Sequence Items
• Sequence items are accessed by numerical index, starting
  at 0.
• To access an individual element, type the sequence name,
  followed by the element's numerical index enclosed within
  square brackets:
 var days = ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"];

 println(days[0]); // prints Mon
 println(days[1]); // prints Tue
 println(days[2]);
 println(days[3]);
 println(days[4]);
 println(days[5]);
Size of a Sequence
• You can determine the size of a sequence using the
  sizeof operator followed by the name of the sequence
  > sizeof days
• The following code prints "7" to the screen:
  > var days = ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"];
  > println(sizeof days);
Inserting Items to a Sequence
• The insert keyword allows you to insert an element into
  a sequence, before a specific element, or after a
  specific element.
 var days = ["Mon"];
 // The sequence contains: "Mon" at this 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".
Inserting with “before” & “after”
• Use insert and before keywords to insert an element
  before an element at a given index.
 insert "Thu" before days[2];
 // The sequence now contains: "Mon", "Tue", "Thu", "Fri", "Sat", "Sun".

 insert "wed" after days[1];
 // The sequence now contains: "Mon", "Tue", "Wed", "Thu", "Fri",
 // "Sat", and "Sun".
Deleting Items from a Sequence
• The delete and from keywords make it easy to delete
  items from a 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;
Reversing Items in a Sequence
• Reverse items in a sequence using the reverse
  operator:
 var nums = [1..5];
 reverse nums; // returns [5, 4, 3, 2, 1]
Comparing Sequences
• Sequences are compared for equality by value: if their
  lengths are equal, and their items are equal, then they
  are equal.
 var seq1 = [1,2,3,4,5];
 var seq2 = [1,2,3,4,5];
 println(seq1 == seq2); // prints true
Sequences Slices
• Sequence slices provide access to portions of a
  sequence.
• seq[a..b] - items between index a and index b
 // weekend sequence consisting of only the items "Sat" and "Sun".
 var days = ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"];
 var weekend = days[5..6];
• seq[a..<b] - between index a inclusive and index b
  exclusive
 // weekdays sequence consisting of the items "Mon" through "Fri"
 var days = ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"];
 var weekdays = days[0..<5];
Sequences Slices
• seq[a..] - all items from index a through the end of the
  sequence
 // weekend sequence consisting of only the items "Sat" and "Sun".
 var days = ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"];
 var weekend = days[5..];

• seq[a..<] - everything from index a to the end of the
  sequence, excluding the last element.
 // sequence consisting of the items "Mon" through "Sat".
 var days = ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"];
 var days2 = days[0..<];
Functions
What is a Function?
 • A function is an executable block of code that performs
   a specific task
 • Function code does not execute until it is explicitly
   invoked
    > This makes it possible to run a function from any location
       within your script. It does not matter if the function invocation
       is placed before or after the function definition

add(); // Invoke add function

function add() {
  result = numOne + numTwo;
  println("{numOne} + {numTwo} = {result}");
Passing Arguments to Functions
 • Script functions may also be defined to accept
   arguments.
var result;

add(100,10);

function add(argOne: Integer, argTwo: Integer) {
   result = argOne + argTwo;
   println("{argOne} + {argTwo} = {result}");
}
Returning Values from Functions
    • A function may also return a value to the code that
      invokes it
function add(argOne: Integer, argTwo: Integer) : Integer {
   result = argOne + argTwo;
   println("{argOne} + {argTwo} = {result}");
   return result;

}
Operators
Operators in JavaFX Script
• Operators are special symbols that perform specific
  operations on one or two operands, and then return a
  result.
• The JavaFX Script programming language provides
  > assignment operators
  > arithmetic operators
  > unary operators
  > equality and relational operators
  > conditional operators
  > type comparison operator.
Assignment Operators
• Use it to assign the value on its right to the operand on
  its left:
 result = num1 + num2;
 days = ["Mon","Tue","Wed","Thu","Fri"];
Arithmetic Operators
• Use it to perform addition, subtraction, multiplication,
  and division.
• The mod operator divides one operand by another and
  returns the remainder as its result
 // + (additive operator)
 // - (subtraction operator)
 // * (multiplication operator)
 // / (division operator)
 // mod (remainder operator)

 result = 10;
 result = result mod 7; // result is now 3
Compound assignments
 var result = 0;
 result += 1;
 println(result); // result is now 1

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

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

 result /= 2; // result is now 5
 println(result);
Unary Operators
// - Unary minus operator; negates a number
// ++ Increment operator; increments a value by 1
// -- Decrement operator; decrements a value by 1
// not       Logical complement operator; inverts the value of a boolean
 var result = 1; // result is now 1

result--; // result is now 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
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
Expressions
Expression in JavaFX Script
• Expressions are pieces of code that evaluate to a result
  value, and that can be combined to produce "bigger"
  expressions.
• The JavaFX Script programming language is an
  expression language, which means that everything,
  including loops, conditionals, and even blocks, are
  expressions.
• In some cases (such as while expressions) the
  expressions have Void type, which means they don't
  return a result value.
Types of Expression
•   Block expression
•   if expression
•   Range expression
•   for expression
•   while expression
•   break and continue expression
•   throw, try, catch, and finally expression
Block Expression
• A block expression consists of a list of declarations or
  expressions surrounded by curly braces and separated
  by semicolons.
• The value of a block expression is the value of the last
  expression.
  > If the block expression contains no expressions, the block
    expression has Void type.
  > Note that var and def are expressions.
Example: Block Expression

 var nums = [5, 7, 3, 9];
 var total = {
     var sum = 0;
     for (a in nums) { sum += a };
     sum;
 }
 println("Total is {total}."); // Total is 24.
if Expression
• if (booleanExpression) then a else b
• if (booleanExpression) a else b
• if (booleanExpression) { a } else { b }
for Expression
• for (i in sequence) { ... }
Range Expression
• By default the interval between the values is 1, but you
  can use the step keyword to specify a different interval.
 var num = [0..5];

 // Use step keyword to specify a different 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);
Access Modifiers
Access Modifiers
• Allow you to set various levels of visibility for your
  variables, functions, and classes (like in Java)
• Access modifiers
  > Default Access
  > The package Access Modifier
  > The protected Access Modifier
  > The public Access Modifier
  > The public-read Access Modifier
  > The public-init Access Modifier
JavaFX
GUI Basics




             1
Quick JavaFX GUI
Overview
User Interface Elements
• Standard UI components you can create using the
  javafx.ext.swing package.
Colors
• Color patterns for all constants of the
  javafx.scene.paint.Color class
Shapes and Fill Styles
• javafx.scene.shape and javafx.scene.paint packages
Text
• Different formatting styles applied to the same text
  string
Effects
• Effects can be applied to the JavaFX UI elements
Transformation
• Transformations can be performed for the graphics,
  images, or text
Layout
• There are several methods of laying out UI elements
  using the javafx.scene.layout package.
•
•
Cursors
• Different views of cursor you can apply to any UI
  element
Using Declarative Syntax
(for Creating GUI)
Why Declarative Syntax for Building
GUI?
• Because the structure of declared objects in the code
  reflects the visual structure of the scene graph, and this
  enables you to understand and maintain the code
  easily.
• The order of elements you declare in the code matches
  the order in which they appear in the application.
Step by Step Process of
Creating a Simple GUI
Step by Step Process of Creating a
simple GUI
• JavaFX application that renders a green rounded
  rectangle and a white circle with red outline on the top
  of the rectangle
Step by Step Process of Creating a
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)
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
2. Create an Application Window
 • In order to display the graphics, you need to create
   a window through Stage object literal
// Create a Stage object literal. Stage is required to render any object.
// The window should be big enough to display all of the rectangle and
// the circle. In this example, the window is a rectangle of 249 by 251
// pixels. To create a window of this size, with a "Declaring is Easy" title,
// declare these values within the curly brackets using the following code:

Stage {
  title: "Declaring Is Easy!"
  width: 249
  height: 251
  visible: true
}
3. Set the Scene
• Within the stage, set the scene to hold Node objects
  such as a circle or a rectangle
• The scene is a root area where you place objects of
  the node type.
• The scene has content variable that is used to hold
  the nodes.
• There are many different kinds of nodes, such as
  graphical objects, text, and GUI components.
3. Set the Scene (Continued)

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

Stage {

    ...
    scene: Scene {
      content: [ ]
    }
}
4. Create a 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
       }
     ]
 }
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
       }
     ]
 }
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 {
            ...
         }
      ]
  }
}
JavaFX Application
Structure
Stage
• Top-level container for a scene
  > Contains only one Scene
• Potentially represented by
  > JFrame on desktop
  > JApplet on web page
  > SVG player on mobile
• Defines the characteristics like title, width, height,
  location, handling exit, etc
Example: Stage
Stage {
  title: "Welcome to JavaFX!"
  scene: Scene {
      content: [
         Text {
           content: "Hello World!"
           x:25 y:25
           fill: Color.BLACK
           font: Font{ size: 32 }
         }
      ]
  }
}
Scene
•   Canvas upon which Scene Graph is displayed
•   Can set multiple CSS stylesheets
•   Can set background color (or set to null)
•   Can set canvas width/height
Scene Graph
What is Scene Graph?
• The scene graph is a tree-like data structure which
  defines a hierarchy of graphical objects in a scene.
• A single element in the scene graph is called a node.
  > Each node has one parent except for the root node, which
    has no parent.
  > Each node is either a leaf node or a branch.
  > A leaf node has no children.
  > A branch node has zero or more children.
JavaFX Architecture

     JavaFX Script Software
                                 Models a GUI
        Project Scene Graph      part of a
                                 JavaFX
                       Effects   application

        Java 2D


       Graphics hardware
Basic Graphical Objects
• Graphical objects as examples of Nodes
  > Text, geometric shapes, text, Swing components
• Some common attributes in nodes
  > Transformation – translate, shear, rotate, scale
  > Clip – displaying only part of the node based on a geometric
    shape
  > Effect – type of effect, eg. blurring, shadowing, to apply
  > Events – mouse, keyboard
  > Opacity – setting the translucency
What is Scene Graph?
• A hierarchical representation of graphical objects
 > Tree like structure
 > Basis of JavaFX graphics engine
• Scene graph elements
 > Nodes – images, text, Swing widgets
 > State – visibility, opacity, transformation
 > Events – mouse, keyboard, node updates
 > Animation – varying properties over time
• A scene graph knows how to render itself!!
 > JavaFX scene graph engine is available at
   http://scenegraph.dev.java.net
 > Usable from Java
Scene Graph: Group
• Group stands a set of Nodes which may have same
  effect
• Group itself is a Node, so can be nested
Scene Graph: Group
Group {
   transforms: Translate {                    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
       }
   ]
}
Shapes
Shapes
•   Arc       •   Rectangle
•   Circle    •   stroke
•   Ellipse   •   strokeWidth
•   Line      •   fill
•   Path      •   smooth
•   Polygon
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
 }
Custom Shapes
• Two ways of defining custom shapes
  > Combining existing shapes
  > Drawing a totally new shape
• Combine existing shape with ShapeIntersect
   or ShapeSubtract
  > Either add or subtract from shape
• Draw new shapes with Path and path elements
  > Path elements include MoveTo, ArcTo, HLine, VLine, QuadCurve,
    etc.
• Can be manipulated like a regular geometric shape
Example – ShapeIntersect
ShapeIntersect {
   transforms: [ Translate { x: 170 } ]
   fill: Color.LIGHTGREEN
   stroke: Color.GREEN
   strokeWidth: 3
   //Union of the 2 shapes
   a: [rectangle diamond ]
}
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},
    ]
}
Other Graphical Objects
Text
• x, y, TextOrigin
• By default, text positioned such that (x, y) is left
  baseline
• Fonts can be specified on Text
• Favor “fill” over “stroke”
• Supports multiple text
• Use Alignment to align multi-line text
• To center text, compute the center via layout bounds
Text
• Defines a node for displaying 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"
 }
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
Images
ImageView = ImageView {
    clip: Rectangle {
        y: 30 x: 50
        width: 350 height: 100
    }
    image: Image { url: "..."}
}
TextBox
• Used for text input
• Use CSS to style the TextBox
• “text” is changed to reflect the actual text in the TextBox
• “value” is changed when the text is “committed” via
  ENTER, TAB, etc
• “action” function is invoked when ENTER is pressed
• “columns” specifies the preferred width based on the
  font size and number of characters to display
Effects
How Effect Works
• javafx.scene.effect package API.
• All of the core filter effect classes extend the abstract
  javafx.scene.effect.Effect base class.
• Any Effect instance can be applied to a scene graph
  Node by setting the Node.effect variable.
• Each Effect subclass exposes a small number of
  variables that control the visual appearance of the
  Node.
• In addition, most Effect subclasses provide one or more
  input variables that can be used to "chain" effects
Variables In a Effect Class
• Each variable is generally documented with default,
  minimum, maximum, and identity values, which makes
  it easy to see the acceptable range of values.
• Developer only need to concern yourself with turning
  the values of these variables.
• The effects framework does all the heavy lifting for you,
  such as painting the Node into an offscreen image at
  the appropriate resolution, manipulating the pixels in
  one of the CPU and/or GPU accelerated backends, and
  automatically repainting the affected portion of the
  scene.
Effects:
DropShadow
Example: DropShadow class
• DropShadow class provides 5 variables
  > color: The shadow Color
       > default: Color.BLACK
  >   offsetX: The shadow offset in the x direction, in pixels.
       > default: 0.0
  >   offsetY: The shadow offset in the y direction, in pixels.
       > default: 0.0
  >   radius: The radius of the shadow blur kernel.
       > default: 10.0, max: 63.0
  >   spread: The spread of the shadow.
       > default: 0.0, max: 1.0, min: 0.0
Example: DropShadow
  Text {
      effect: DropShadow {
         offsetY: 3
         color: Color.color(0.4, 0.4, 0.4)
      };
     ...
  },
  Circle {
      effect: DropShadow {
         offsetY: 4
      },
     ...
  }
Example: DropShadow
  Text {
      effect: DropShadow {
         offsetY: 3
         color: Color.GREEN
         radius: 20.0
      };
     ...
  },
  Circle {
      effect: DropShadow {
         offsetX: 10
         offsetY: 20
         color: Color.BLUE
         radius: 30.0
      }
Effects:
Lighting
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
    }
 }
Effects:
PerspectiveTransform
PerspectiveTransform Class
 • Used to provide a "faux" three-dimensional effect for
   otherwise two-dimensional content.
Group {
  effect: PerspectiveTransform {
     ulx: 10 uly: 10 urx: 310 ury: 40
     lrx: 310 lry: 60 llx: 10 lly: 90
  }
  cache: true
  content: [
     Rectangle {
        x: 10 y: 10 width: 280 height: 80 fill: Color.BLUE
     },
     Text {
        x: 20 y: 65 content: "Perspective" fill: Color.YELLOW
        font: Font.font(null, FontWeight.BOLD, 36);
     },
  ]
Effects:
Linear Gradients
Linear Gradients
• startX, startY, endX, endY
  > Define the direction of the gradient
  > On the unit square
• Stops define each step in the gradient.
• Each stop
  > Has an offset between 0...1
  > Has a color
Effects:
Glow, Reflection,
GaussianBlur
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 }
JavaFX Script
Language: Data
binding & Triggers




                     1
What is Binding?
What is & Why (Data) Binding?
• Data binding refers to the language feature of JavaFX
  script of creating an immediate and direct relationship
  between two variables,
• Data binding is one of the most powerful features of the
  JavaFX Script programming language.
• In most real-world programming situations, you will use
  data binding to keep an application's Graphical User
  Interface (GUI) in sync with its underlying data.
How Binding Works
• Cause and effect – responding to changes
• bind operator allows dynamic content to be expressed
  declaratively
• Dependency based evaluation of any expression
• Automated by the JavaFX runtime rather than manually
  wired by the programmer
• Eliminates the listener pattern
Binding
• The bind keyword associates the value of a target
  variable with the value of a bound expression.
• The bound expression can be a simple value of
  > some basic type
  > an object
  > outcome of a function
  > outcome of an expression.
Binding to a Variable
of Basic Type
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
Binding to an Object
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”
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”
Binding to a Function
Binding and Functions
• There is a difference between “binding to a bound
  function” vs. “binding to a non-bound function”.
  > Binding to a “bound function” - change for the value of a non-
    function-argument invoke the function
  > Binding to a “non-bound function” - change for the value of a
    non-function-argument does not invoke the function
Definition of a Bound 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;
}
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
Transformation
Transformation class
• Provides functions to perform
  > rotating
  > scaling
  > shearing
  > translation
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
                }
                ...
            }
        ]
    }
}
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
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;
                }
            }
        ]
    }
}
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;
                }
            }
        ]
Interactions
Handling Events
• All nodes have either mouse or keyboard events
  > Override the appropriate method
• Mouse events – onMouseXXXX()
  > XXXX = Entered, Exited, Pressed, Dragged, Moved, Clicked,
    Released, WheelMoved
• Keyboard events – onKeyboardXXXX()
  > XXXX = Pressed, Released, Typed
• Indicate interactivity by changing cursor
  > Set the cursor attribute
Example: Handling Events
• Mouse events change the color of an 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;
    }
}
Drag and Drop
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;
   }
}

More Related Content

What's hot

20160520 what youneedtoknowaboutlambdas
20160520 what youneedtoknowaboutlambdas20160520 what youneedtoknowaboutlambdas
20160520 what youneedtoknowaboutlambdasshinolajla
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scalapramode_ce
 
DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#Rasan Samarasinghe
 
Esoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programmingEsoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programmingRasan Samarasinghe
 
Developer’s viewpoint on swift programming language
Developer’s viewpoint on swift programming languageDeveloper’s viewpoint on swift programming language
Developer’s viewpoint on swift programming languageAzilen Technologies Pvt. Ltd.
 
TEMPLATES IN JAVA
TEMPLATES IN JAVATEMPLATES IN JAVA
TEMPLATES IN JAVAMuskanSony
 

What's hot (20)

Javascript 101
Javascript 101Javascript 101
Javascript 101
 
Intro to Scala
 Intro to Scala Intro to Scala
Intro to Scala
 
Xtext Webinar
Xtext WebinarXtext Webinar
Xtext Webinar
 
Javascript
JavascriptJavascript
Javascript
 
06 ruby variables
06 ruby variables06 ruby variables
06 ruby variables
 
DIWE - Advanced PHP Concepts
DIWE - Advanced PHP ConceptsDIWE - Advanced PHP Concepts
DIWE - Advanced PHP Concepts
 
20160520 what youneedtoknowaboutlambdas
20160520 what youneedtoknowaboutlambdas20160520 what youneedtoknowaboutlambdas
20160520 what youneedtoknowaboutlambdas
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scala
 
Client sidescripting javascript
Client sidescripting javascriptClient sidescripting javascript
Client sidescripting javascript
 
Overview of CoffeeScript
Overview of CoffeeScriptOverview of CoffeeScript
Overview of CoffeeScript
 
Linq Introduction
Linq IntroductionLinq Introduction
Linq Introduction
 
Getting rid of backtracking
Getting rid of backtrackingGetting rid of backtracking
Getting rid of backtracking
 
Javascript basics
Javascript basicsJavascript basics
Javascript basics
 
Comp102 lec 4
Comp102   lec 4Comp102   lec 4
Comp102 lec 4
 
DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#
 
Esoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programmingEsoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programming
 
camel-scala.pdf
camel-scala.pdfcamel-scala.pdf
camel-scala.pdf
 
Developer’s viewpoint on swift programming language
Developer’s viewpoint on swift programming languageDeveloper’s viewpoint on swift programming language
Developer’s viewpoint on swift programming language
 
TEMPLATES IN JAVA
TEMPLATES IN JAVATEMPLATES IN JAVA
TEMPLATES IN JAVA
 
Writing Parsers and Compilers with PLY
Writing Parsers and Compilers with PLYWriting Parsers and Compilers with PLY
Writing Parsers and Compilers with PLY
 

Viewers also liked

What's New in Java 8
What's New in Java 8What's New in Java 8
What's New in Java 8javafxpert
 
Java FX 2.0 - A Developer's Guide
Java FX 2.0 - A Developer's GuideJava FX 2.0 - A Developer's Guide
Java FX 2.0 - A Developer's GuideStephen Chin
 
Cleaner APIs, Cleaner UIs with Visage (33rd Degrees)
Cleaner APIs, Cleaner UIs with Visage (33rd Degrees)Cleaner APIs, Cleaner UIs with Visage (33rd Degrees)
Cleaner APIs, Cleaner UIs with Visage (33rd Degrees)Stephen Chin
 
Raspberry Pi Gaming 4 Kids (Devoxx4Kids)
Raspberry Pi Gaming 4 Kids (Devoxx4Kids)Raspberry Pi Gaming 4 Kids (Devoxx4Kids)
Raspberry Pi Gaming 4 Kids (Devoxx4Kids)Stephen Chin
 
Confessions of a Former Agile Methodologist (JFrog Edition)
Confessions of a Former Agile Methodologist (JFrog Edition)Confessions of a Former Agile Methodologist (JFrog Edition)
Confessions of a Former Agile Methodologist (JFrog Edition)Stephen Chin
 
Oracle IoT Kids Workshop
Oracle IoT Kids WorkshopOracle IoT Kids Workshop
Oracle IoT Kids WorkshopStephen Chin
 
Devoxx4Kids NAO Workshop
Devoxx4Kids NAO WorkshopDevoxx4Kids NAO Workshop
Devoxx4Kids NAO WorkshopStephen Chin
 
Devoxx4Kids Lego Workshop
Devoxx4Kids Lego WorkshopDevoxx4Kids Lego Workshop
Devoxx4Kids Lego WorkshopStephen Chin
 
What is tackled in the Java EE Security API (Java EE 8)
What is tackled in the Java EE Security API (Java EE 8)What is tackled in the Java EE Security API (Java EE 8)
What is tackled in the Java EE Security API (Java EE 8)Rudy De Busscher
 

Viewers also liked (9)

What's New in Java 8
What's New in Java 8What's New in Java 8
What's New in Java 8
 
Java FX 2.0 - A Developer's Guide
Java FX 2.0 - A Developer's GuideJava FX 2.0 - A Developer's Guide
Java FX 2.0 - A Developer's Guide
 
Cleaner APIs, Cleaner UIs with Visage (33rd Degrees)
Cleaner APIs, Cleaner UIs with Visage (33rd Degrees)Cleaner APIs, Cleaner UIs with Visage (33rd Degrees)
Cleaner APIs, Cleaner UIs with Visage (33rd Degrees)
 
Raspberry Pi Gaming 4 Kids (Devoxx4Kids)
Raspberry Pi Gaming 4 Kids (Devoxx4Kids)Raspberry Pi Gaming 4 Kids (Devoxx4Kids)
Raspberry Pi Gaming 4 Kids (Devoxx4Kids)
 
Confessions of a Former Agile Methodologist (JFrog Edition)
Confessions of a Former Agile Methodologist (JFrog Edition)Confessions of a Former Agile Methodologist (JFrog Edition)
Confessions of a Former Agile Methodologist (JFrog Edition)
 
Oracle IoT Kids Workshop
Oracle IoT Kids WorkshopOracle IoT Kids Workshop
Oracle IoT Kids Workshop
 
Devoxx4Kids NAO Workshop
Devoxx4Kids NAO WorkshopDevoxx4Kids NAO Workshop
Devoxx4Kids NAO Workshop
 
Devoxx4Kids Lego Workshop
Devoxx4Kids Lego WorkshopDevoxx4Kids Lego Workshop
Devoxx4Kids Lego Workshop
 
What is tackled in the Java EE Security API (Java EE 8)
What is tackled in the Java EE Security API (Java EE 8)What is tackled in the Java EE Security API (Java EE 8)
What is tackled in the Java EE Security API (Java EE 8)
 

Similar to Java Fx (20)

Presentation - Course about JavaFX
Presentation - Course about JavaFXPresentation - Course about JavaFX
Presentation - Course about JavaFX
 
WT Unit-3 PPT.pptx
WT Unit-3 PPT.pptxWT Unit-3 PPT.pptx
WT Unit-3 PPT.pptx
 
Java ce241
Java ce241Java ce241
Java ce241
 
Java script basics
Java script basicsJava script basics
Java script basics
 
Complete Notes on Angular 2 and TypeScript
Complete Notes on Angular 2 and TypeScriptComplete Notes on Angular 2 and TypeScript
Complete Notes on Angular 2 and TypeScript
 
gdscWorkShopJavascriptintroductions.pptx
gdscWorkShopJavascriptintroductions.pptxgdscWorkShopJavascriptintroductions.pptx
gdscWorkShopJavascriptintroductions.pptx
 
Presentation 2nd
Presentation 2ndPresentation 2nd
Presentation 2nd
 
Javascript Basics by Bonny
Javascript Basics by BonnyJavascript Basics by Bonny
Javascript Basics by Bonny
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Variables
VariablesVariables
Variables
 
Dart programming language
Dart programming languageDart programming language
Dart programming language
 
JavaScript Lecture notes.pptx
JavaScript Lecture notes.pptxJavaScript Lecture notes.pptx
JavaScript Lecture notes.pptx
 
Javascript
JavascriptJavascript
Javascript
 
Unit 1
Unit 1Unit 1
Unit 1
 
What’s new in .NET
What’s new in .NETWhat’s new in .NET
What’s new in .NET
 
Javascript
JavascriptJavascript
Javascript
 
Qtp - Introduction to fundamentals of vbscript
Qtp - Introduction to fundamentals of vbscriptQtp - Introduction to fundamentals of vbscript
Qtp - Introduction to fundamentals of vbscript
 
Java introduction
Java introductionJava introduction
Java introduction
 
Final Java-script.pptx
Final Java-script.pptxFinal Java-script.pptx
Final Java-script.pptx
 
C# 7 development
C# 7 developmentC# 7 development
C# 7 development
 

More from Karthik Sankar

Clearing the air on Cloud Computing
Clearing the air on Cloud ComputingClearing the air on Cloud Computing
Clearing the air on Cloud ComputingKarthik Sankar
 
The Science of Violin Harmonics with special focus on Articulation, Vibrato a...
The Science of Violin Harmonics with special focus on Articulation, Vibrato a...The Science of Violin Harmonics with special focus on Articulation, Vibrato a...
The Science of Violin Harmonics with special focus on Articulation, Vibrato a...Karthik Sankar
 
Realizing Parallelism and Transparency in Applications through Idempotence
Realizing Parallelism and Transparency in Applications through IdempotenceRealizing Parallelism and Transparency in Applications through Idempotence
Realizing Parallelism and Transparency in Applications through IdempotenceKarthik Sankar
 
Tamil Morphological Analysis
Tamil Morphological AnalysisTamil Morphological Analysis
Tamil Morphological AnalysisKarthik Sankar
 
Natural Language Processing and Machine Learning
Natural Language Processing and Machine LearningNatural Language Processing and Machine Learning
Natural Language Processing and Machine LearningKarthik Sankar
 

More from Karthik Sankar (9)

Clearing the air on Cloud Computing
Clearing the air on Cloud ComputingClearing the air on Cloud Computing
Clearing the air on Cloud Computing
 
The Science of Violin Harmonics with special focus on Articulation, Vibrato a...
The Science of Violin Harmonics with special focus on Articulation, Vibrato a...The Science of Violin Harmonics with special focus on Articulation, Vibrato a...
The Science of Violin Harmonics with special focus on Articulation, Vibrato a...
 
Realizing Parallelism and Transparency in Applications through Idempotence
Realizing Parallelism and Transparency in Applications through IdempotenceRealizing Parallelism and Transparency in Applications through Idempotence
Realizing Parallelism and Transparency in Applications through Idempotence
 
Rates of exchange
Rates of exchangeRates of exchange
Rates of exchange
 
Tamil Morphological Analysis
Tamil Morphological AnalysisTamil Morphological Analysis
Tamil Morphological Analysis
 
Genetic Algorithms
Genetic AlgorithmsGenetic Algorithms
Genetic Algorithms
 
Natural Language Processing and Machine Learning
Natural Language Processing and Machine LearningNatural Language Processing and Machine Learning
Natural Language Processing and Machine Learning
 
Sadhana
SadhanaSadhana
Sadhana
 
Cloud Computing
Cloud ComputingCloud Computing
Cloud Computing
 

Recently uploaded

Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 

Recently uploaded (20)

Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 

Java Fx

  • 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
  • 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
  • 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 } } ] } }
  • 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."); } }
  • 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.
  • 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}"); }
  • 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 }
  • 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..<];
  • 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; }
  • 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
  • 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);
  • 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
  • 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
  • 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 { ... } ] } }
  • 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
  • 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}, ] }
  • 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
  • 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.
  • 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 }
  • 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 } }
  • 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); }, ]
  • 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
  • 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 }
  • 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
  • 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; } } ]
  • 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; } }
  • 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; } }