JavaFX: Bringing Rich Experiences To All the Screens Of Your Life

expand all

Profile: desktop, common

JavaFX 1.3.1 API | Overview | Java FX

com.javafx.preview.control

This package contains a collection of experimental/preview controls that are not final and will change in future releases.

This package contains a collection of experimental/preview controls that are not final and will change in future releases. Eventually it is intended that these controls will transition from the com.javafx.preview.control package to the javafx.scene.control package.

These controls have been made available for early adopters to experiment with in the hopes that doing so will provide useful feedback to help make the JavaFX UI Controls library the most powerful and pleasing UI Controls library available. If you have any feedback on these controls, either as requests for enhancement or as bug reports, please report them all to the JavaFX JIRA issue tracker.

For more information on the official controls that are part of the JavaFX release, as well as details on the controls architecture and how to style controls, refer to the javafx.scene.control package information page.

 
com.javafx.preview.layout
javafx.animation

The javafx.animation package provides a set of classes that implement a time-based animation framework.

The javafx.animation package provides a set of classes that implement a time-based animation framework. This framework allows an application to define values for a set of variables at particular points in time, thus creating a mapping from time to value for each target variable.

The two primary classes in this package are:

  • Timeline – Controls the execution of a sequence of key frames, processing each KeyFrame sequentially, in the order specified by the KeyFrame.time variable. The repeatCount variable specifies how many times a Timeline will run before stopping, or specifies that the Timeline will run indefinitely (until explicitly stopped). A Timeline that runs more than once will restart each pass at the beginning of the Timeline, unless the autoReverse flag is set, which will cause the Timeline to reverse direction for each pass.

  • KeyFrame – Defines target values at a specified point in time for a set of variables that are interpolated along a Timeline. A KeyFrame optionally defines an action function that is called when the KeyFrame is executed

Each variable in the Timeline transitions between the declared values at each KeyFrame, by using the declared interpolation function to calculate the in-between value at that time. The default interpolator performs linear interpolation, although other interpolators are available (for example, EASEIN, EASEOUT, and EASEBOTH).

These interpolated variables can then be used to control various rendering attributes (such as position), or for any other use desired by the application.

For example:

    import javafx.animation.Timeline;
    import javafx.animation.KeyFrame;
    
    var x:Number;
    
    var tl = Timeline {
        keyFrames: [
            KeyFrame {
                time: 0s
                values: x => 1.0
            }
            KeyFrame {
                time: 2s
                values: x => 5.0
            }
        ]
    }
    

When the above Timeline is played, the variable x will linearly transition from a value of 1.0 at time = 0 seconds (that is, right after the Timeline starts playing) to a value of 5.0 at time = 2 seconds.

Note that the JavaFX compiler has built-in support for animation. Along with the => operator, the at() pseudo-function makes defining a KeyFrame and its associated key values even easier:

    import javafx.animation.Timeline;
    
    var x:Number;
    
    var tl = Timeline {
        keyFrames: [
            at(0s) { x => 1.0 }
            at(2s) { x => 5.0 }
        ]
    }
    

In addition to defining key values, a KeyFrame can have an action associated with it. This action function is called when the Timeline reaches the particular point in time.

For example:

    import javafx.animation.Timeline;
    import javafx.animation.KeyFrame;
    import javafx.animation.Interpolator;
    
    var x:Number;
    var y:Number;
    
    var tl = Timeline {
        repeatCount: Timeline.INDEFINITE
        keyFrames: [
            at(0s) { x => 1.0; y => 3.0 }
            at(2s) { x => 4.0 }
            at(4s) { x => 5.0; y => 12.0 tween Interpolator.EASEBOTH }
            KeyFrame {
                time: 4s
                action: function() {
                    println("done with cycle");
                }
            }
        ]
    }
    

In this example, x will linearly interpolate from 1.0 to 4.0 over the first 2 seconds, and then from 4.0 to 5.0 over the next 2 seconds. Because there is no value for y defined at time = 2 seconds, y will interpolate from 3.0 to 12.0 over 4 seconds using an easing interpolator at the beginning and end of the interval. At the end of 4 seconds the final KeyFrame will execute its action function and print the message "done with cycle". The final KeyFrame uses an explicit object literal because there is no shorthand form that includes the action function.

Note that this Timeline has a repeatCount of INDEFINITE, so it will run continuously, starting over at time = 0 every 4 seconds, immediately after executing the KeyFrame(s) at time = 4 seconds.

 
javafx.animation.transition

Provides the set of classes for ease of use transition based animations.

Provides the set of classes for ease of use transition based animations.

It offers a simple framework for incorporating animations onto an internal Timeline. It also provides high level constructs to compose the effects of multiple animations.

 
javafx.async

Provides the set of classes for javafx.async.

Provides the set of classes for javafx.async.

This package provides the ability to run application code on threads other than the JavaFX event dispatch thread. The ability to control the execution and track the progress of the application code is also provided.

 
javafx.data
javafx.data.feed

This package contains the base classes for an Atom or RSS document.

This package contains the base classes for an Atom or RSS document.

 
javafx.data.feed.atom

This package contains all the data structures for parsing a document that conforms to the Atom Syndication Format

This package contains all the data structures for parsing a document that conforms to the Atom Syndication Format

 
javafx.data.feed.rss

This package contains all the data structures for parsing an RSS document.

This package contains all the data structures for parsing an RSS document.

 
javafx.data.pull
javafx.data.xml
javafx.date
javafx.ext.swing

Provides the set of graphical user interface component classes that, to the maximum degree possible, work the same on all platforms.

Provides the set of graphical user interface component classes that, to the maximum degree possible, work the same on all platforms.

This is a second paragraph test.

 
javafx.fxd

Provides functionality to load JavaFX graphic files (FXD and FXZ format) that are generated by JavaFX Production Suite.

Provides functionality to load JavaFX graphic files (FXD and FXZ format) that are generated by JavaFX Production Suite. JavaFX graphic format files contains text descriptions of the graphical content of the JavaFX application. Descriptions are loaded by this package into the application during runtime. JavaFX graphic format exists in two forms, FXD and FXZ. FXD is a textual format using the same object literal syntax as JavaFX Script, so it is possible to copy and paste the descriptions from the FXD file directly into JavaFX Script code (with some exceptions noted at the end of this section). Here is an example of a simple FXD file representing a smiley face graphic:

FXD {
  content: [
    Circle { id:"background" centerX:40 centerY:40 radius:39
             fill:Color.YELLOW stroke:Color.BLACK strokeWidth:3.0},
    Circle { centerX:25 centerY:30 radius:5 fill: Color.BLACK},
    Circle { centerX:55 centerY:30 radius:5 fill: Color.BLACK},
    Line{ startX:32 startY:23 endX:16 endY:15 stroke:Color.BLACK strokeWidth:4.0},
    Line{ startX:45 startY:23 endX:61 endY:15 stroke:Color.BLACK strokeWidth:4.0},
    QuadCurve { id: "mouth" stroke:Color.BLACK  strokeWidth:3.0 fill: Color.TRANSPARENT
                startX:20 startY:60 endX:60 endY:60 controlX:40 controlY:80
    }
  ]
}
The content is loaded using the javafx.fxd.FXDLoader class. It can be inserted into the scene graph using this snippet of code:
var group:Group .... // a graphics group defined elsewhere 
var smileyNode = FXDLoader.load("{__DIR__}smiley.fxd"}; // loads the content
insert smileyNode into group.content; // inserts the smiley into the group
It is possible to reference external assets from FXD content. The FXD description follows the same approach as JavaFX Script, using the {__DIR__} magic variable. The following example demonstrates how to reference embedded font and image files in the FXD description. All of the files are stored in an FXZ file called mygfx.fxz:
FXD {
  content: [
    ImageView { x: 10 y: 10
               image: Image{ url: "{__DIR__}myimage.png"}
    },
    Text { fill: Color.WHITE x: 20 y: 20 textOrigin: TextOrigin.TOP
           font: Font.fontFromURL("{__DIR__}myfont.ttf", 25.00)
           content: "Welcome !!!"
    },
  ]
}
In the above example, the root contains two nodes - ImageView with Image, which loads its content from the myimage.png file. The other node is a Text node and it uses a custom font with size 25. The font is loaded from the myfont.ttf file. Both, the image and the font files are located in the same directory as the mygfx.fxd file itself. FXZ is simply a compressed version of the FXD content using zip compression and file format. The FXZ file can also contain embedded assets, such as images or fonts. The structure of the FXZ file from the example above is as follows:
mygfx.fxz
 +- content.fxd
 +- myimage.png
 +- myfont.ttf
 +- ...
The content.fxd file is the main content of the FXZ archive, containing the description of the graphic objects. The other files, myimage.png and myfont.ttf are the embedded image and font assets. FXZ files can be loaded in exactly the same way as FXD files, using the javafx.fxd.FXDLoader class. FXD format follows similar object literal syntax as JavaFX Script. This makes FXD format highly compatible with JavaFX Script, and it is possible to copy portions of the FXD content directly to the JavaFX script code. Detailed FXD format specification is available here.

 

 
javafx.geometry

Provides the set of 2D classes for defining and performing operations on objects related to two-dimensional geometry.

Provides the set of 2D classes for defining and performing operations on objects related to two-dimensional geometry.

 
javafx.io

Provides basic IO facility for JavaFX scripts.

Provides basic IO facility for JavaFX scripts.

The main areas of functionality of javafx.io package include

  1. Storage: Represents each storage entry in the system. Also provides APIs for application wide statistics & operations.

  2. Resource: Provides a view of contents of a single stored entity.

 
javafx.io.http

This package contains the classes for communicating via HTTP.

This package contains the classes for communicating via HTTP.

 
javafx.lang

This package provides JavaFX Script Runtime APIs

This package provides JavaFX Script Runtime APIs

Builtins

This class is automatically imported to all JavaFX Scripts

FX

The FX class contains number of static entry points for a couple of different API sets provided by JavaFX Script.
  • Application Model

    JavaFX Script APIs are categorized into following profiles.

    • Common Profile

      This API is common across all platforms

    • Desktop Profile

      This API is available only in the desktop environment (browser & standalone)

    • Mobile Profile

      This API is available only in the mobile environment.

    If an application needs to be portable across all screens, it has to limit itself to common profile APIs. The JavaFX Script Runtime has the ability to run JavaFX Scripts that use the common or desktop API sets in any supported Browser.

  • Argument or Parameter Handling

    JavaFX Scripts can get Arguments or Parameters in 2 different forms

    • Named

      Named Parameters come in the form of a Name, Value pair typically from HTML, JAD or JNLP files. They can also be passed as a commandline argument in the form of "name=value".

      Use the getArgument() api for Named parameters

    • Unnamed

      Unnamed Arguments are always passed on the commandline.

      Use the FX.getArguments() api for Named parameters

    These cannot be combined, if they are it will behave as space seperated arguments.

  • SystemProperty information

 
javafx.reflect

Provides reflective access to JavaFX values and types.

Provides reflective access to JavaFX values and types. This packages defines a Java API (rather than a JavaFX API), so it can be used from both Java and JavaFX code. A future JavaFX API may be layered on top of this.

Context

The objects in this package are directly or indirectly created from a FXContext. In the default case there is a single FXContext instance that uses Java reflection. You get one of these by doing:
 FXLocal.Context ctx = FXLocal.getContext();
 
Alternatively, you can do:
 FXContext ctx = FXContext.getInstance();
 
The latter is more abstract (as it supports proxying for remote VMs) but the more specific FXLocal.Context supports some extra operations that only make sense for same-VM reflection.

Values

The various reflection operations do not directly use Java values. Instead, an javafx.reflect.FXObjectValue is a handle or proxy for an Object. This extra layer of indirection isn't needed in many cases, but it is useful for remote invocation, remote control, or in general access to data in a different VM.

Object creation

To do the equivalent of the JavaFX code:
 var x = ...;
 var z = Foo { a: 10; b: bind x.y };
 
you can do:
 FXContext rcontext = ...;
 FXClassType cls = rcontext.findClass(...);
 FXObjectValue x = ...;
 FXObjectValue z = cls.allocation();
 z.initVar("a", ???);
 z.bindVar("b", ???);
 z.initialize();
 

Sequence operations

Use javafx.reflect.FXSequenceBuilder to create a new sequence.

To get the number of items in a sequence, use ValueRef.getItemCount. To index into a sequence, use ValueRef.getItem.

Design notes and issues

Some design principles, influenced by the "Mirrored reflection" APIs (Bracha and Ungar: Mirrors: Design Principles for Meta-level Facilities of Object-Oritented Programming Languages, OOPSLA 2004), and JDI :
  • No explicit constructors in user code.
  • Keep everything abstract, and allow indirection. For example, we might be working on objects in the current VM, or a remote VM. We might not have objects at all - a subset of the same API might be used for (say) reading from .class files.
  • Hence the core classes are interfaces or abstract.
  • On the other hand, we should avoid useless levels of indirection or "service lookup".

Limitations

  • Error handling isn't very consistent - sometimes we return null, and sometimes we throw an exception.
  • We don't support bound functions properly.

 
javafx.runtime
javafx.scene

Provides the core set of base classes for the JavaFX Scene Graph API.

Provides the core set of base classes for the JavaFX Scene Graph API. A scene graph is a tree-like data structure, where each item in the tree has zero or one parent and zero or more children.

The two primary classes in this package are:

  • Scene – Defines the scene to be rendered. It contains a fill variable that specifies the background of the scene, width and height variables that specify the size of the scene, and a content sequence that contains a list of "root" Nodes to be rendered onto the scene. This sequence of Nodes is the scene graph for this Scene. A Scene is rendered onto a javafx.stage.Stage, which is the top-level container for JavaFX content.

  • Node – Abstract base class for all nodes in the scene graph. Each node is either a "leaf" node with no child nodes or a "branch" node with zero or more child nodes. Each node in the tree has zero or one parent. Only a single node within each tree in the scene graph will have no parent, which is often referred to as the "root" node. There may be several trees in the scene graph. Some trees may be part of a Scene, in which case they are eligible to be displayed. Other trees might not be part of any Scene.

Branch nodes are of type Parent, whose concrete subclasses are Group, javafx.scene.layout.Container, javafx.scene.control.Control, CustomNode, or subclasses thereof.

Leaf nodes are classes such as javafx.scene.shape.Rectangle, javafx.scene.text.Text, javafx.scene.image.ImageView, javafx.scene.media.MediaView, or other such leaf classes which cannot have children.

A node may occur at most once anywhere in the scene graph. Specifically, a node must appear no more than once in all of the following: in the content sequence of a Scene, in the children sequence of a Parent (for example, in a Group node's content sequence), or as the clip of a Node. See the Node class for more details on these restrictions.

Example

An example JavaFX scene graph is as follows:

    import javafx.scene.Scene;
    import javafx.scene.paint.Color;
    import javafx.scene.shape.Circle;
    import javafx.scene.text.Font;
    import javafx.scene.text.Text;
    
    Scene {
        width: 200
        height: 150
        fill: Color.LIGHTGRAY
        content: [
            Circle {
                centerX: 60
                centerY: 40
                radius: 30
                fill: Color.GREEN
            },
            Text {
                x: 10
                y: 90
                font: Font { size: 20 }
                content: "JavaFX Scene"
                fill: Color.DARKRED
            }
        ]
    }
    

The above example will generate the following image:

Coordinate System and Transformations

The Node class defines a traditional computer graphics "local" coordinate system in which the x axis increases to the right and the y axis increases downwards. The concrete node classes for shapes provide variables for defining the geometry and location of the shape within this local coordinate space. For example, javafx.scene.shape.Rectangle provides x, y, width, height variables while javafx.scene.shape.Circle provides centerX, centerY, and radius.

Any Node can have transformations applied to it. These include translation, rotation, scaling, or shearing transformations. A transformation will change the position, orientation, or size of the coordinate system as viewed from the parent of the node that has been transformed.

See the Node class for more information on transformations.

Bounding Rectangle

Since every Node has transformations, every Node's geometric bounding rectangle can be described differently depending on whether transformations are accounted for or not.

Each Node has the following read-only variables which specifies these bounding rectangles:

  • boundsInLocal – specifies the bounds of the Node in untransformed local coordinates.

  • boundsInParent – specifies the bounds of the Node after all transformations have been applied. It is called "boundsInParent" because the rectangle will be relative to the parent's coordinate system.

  • layoutBounds – specifies the rectangular bounds of the Node that should be used as the basis for layout calculations, and may differ from the visual bounds of the node. For shapes, Text, and ImageView, the default layoutBounds includes only the shape geometry.

See the Node class for more information on bounding rectangles.

CSS

The JavaFX Scene Graph provides the facility to style nodes using CSS (Cascading Style Sheets). The Node class contains id, styleClass, and style variables are used by CSS selectors to find nodes to which styles should be applied. The Scene class contains the stylesheets variable which is a sequence of URLs that reference CSS style sheets that are to be applied to the nodes within that scene.

For further information about CSS, how to apply CSS styles to nodes, and what properties are available for styling, see the CSS Reference Guide.

 
javafx.scene.chart

The JavaFX User Interface provides a set of chart components that are a very convenient way for data visualization.

The JavaFX User Interface provides a set of chart components that are a very convenient way for data visualization. Application developers can make use of these off-the-rack graphical charts provided by the SDK, to visualize a wide variety of data.

Commom types of charts such as Bar, Line, Area, Pie, Scatter and Bubble charts are provided. These charts are easy to create and are customizable. JavaFX Charts API is a visual centric API rather than model centric. There are several public variables provided for charts that can be customized either programmatically or via CSS.

JavaFX Charts API is modular and extendable. PieChart3D and BarChart3D are two such examples that extend from PieChart and BarChart respectively to form new Chart types.

Below is a table listing the existing Chart types and a brief summary of their intended use.

Chart

Summary

LineChart

Plots line between the data points in a series. Used usually to view data trends over time.

AreaChart

Plots the area between the line that connects the data points and the axis. Good for comparing cumulated totals over time.

BarChart

Plots rectangular bars with heights indicating data values they represent, and corresponding to the categories they belongs to. Used for displaying discontinuous / discrete data

PieChart

Plots circular chart divided into segments with each segment representing a value as a proportion of the total. It looks like a Pie and hence the name

BubbleChart

Plots bubbles for data points in a series. Each plotted entity depicts three parameters in a 2D chart and hence a unique chart type.

ScatterChart

Plots symbols for the data points in a series. This type of chart is useful in viewing distribution of data and its corelation, if there is any clustering.

The javafx.scene.chart.Chart is the baseclass for all charts. It is responsible for drawing the background, frame, title and legend. It can be extended to create custom chart types. The javafx.scene.chart.XYChart is the baseclass for all two axis charts and it extends from Chart class. It is mostly responsible for drawing the two axis and the background of the chart plot. Most charts extend from XYChart class except for PieChart which extends from Chart class as it is not a two axis chart.

The javafx.scene.chart.part package includes axis classes that can be used when creating two axis charts. javafx.scene.chart.data.Axis is the abstract base class of all chart axis. javafx.scene.chart.part.CategoryAxis plots string categories where each value is a unique category along the axis. javafx.scene.chart.NumberAxis plots a range of numbers with major tick marks every tickUnit.

The javafx.scene.chart.data package has Data and Series classes that are used as a basis for defining chart data. Chart contains one or several series of data.

For Example BarChart plots data from a sequence of javafx.scene.chart.BarChart.Series objects. Each series contains javafx.scene.chart.BarChart.Data objects.

        def barSeries1: BarChart.Series = BarChart.Series {
            name: "Anvils"
            BarChart.Data {
                Category: "2007"
                Value: 567
            }
        }
        

We can define more series objects similarly. Following code snippet shows how to create a BarChart with 3 categories and its X and Y axis:

        def barchart = BarChart {
            title: "Title" titleFont: Font { size: 24 }
            categoryAxis: CategoryAxis {
            categories: ["2007", "2008", "2009"]
        }
        valueAxis: NumberAxis {
            label: "Units Sold"
            UpperBound: 3000
            tickUnit: 1000
        }
        data: [barSeries1, barSeries2, barSeries3]
      }
       

JavaFX charts lends itself very well for real time or dynamic Charting (like online stocks, web traffic etc) from live data sets. Here is an example of a dynamic chart created with simulated data. A javafx.animation.Timeline is used to simulate dynamic data for temperature variations over time(Days).

            def DISPLAY_RANGE:Integer = 50;
           
            def xAxis:NumberAxis = NumberAxis {
                label: "Time (Days)"
                lowerBound: 0
                upperBound: DISPLAY_RANGE
                tickUnit: DISPLAY_RANGE/10
                formatTickLabel: function(value):String { "{(value as Float) as Integer}" }
            };
            public def CHART =  LineChart {
                title: "Dynamic Data Sample"
                data: LineChart.Series{
                    name: "Random"
                };
                xAxis: xAxis
                yAxis: NumberAxis {
                    label: "Temperature"
                    lowerBound: -40
                    upperBound: 100
                    tickUnit: 20
                }
            }
            var currentDay = 0;
            def timeline:Timeline = Timeline{
                repeatCount: Timeline.INDEFINITE
                keyFrames: KeyFrame {
                    time: 0.2s
                    action: function() {
                        if (currentDay > DISPLAY_RANGE) {
                            delete series.data[0];
                            xAxis.lowerBound = currentDay-DISPLAY_RANGE;
                            xAxis.upperBound = currentDay;
                        }
                        insert LineChart.Data{
                            xValue: currentDay
                            yValue: (javafx.util.Math.random() * 130) -35
                        } into series.data;
                        currentDay ++;
                    }
                }
            }
            

 
javafx.scene.chart.data
javafx.scene.chart.part
javafx.scene.control

The JavaFX User Interface Controls (UI Controls or just Controls) are specialized Nodes in the JavaFX Scenegraph especially suited for reuse in many different application contexts.

The JavaFX User Interface Controls (UI Controls or just Controls) are specialized Nodes in the JavaFX Scenegraph especially suited for reuse in many different application contexts. They are designed to be highly customizable visually by designers and developers. They are designed to work well with layout systems, and to be useful for mobile, desktop, web, and tv applications. Examples of prominent controls include Button, Label, ListView, and TextBox.

Since Controls are Nodes in the scenegraph, they can be freely mixed with Containers, Groups, Images, Media, Text, and basic geometric shapes. While writing new UI Controls is not trivial, using and styling them is very easy, especially to existing web developers.

Below is a table listing the existing UI Controls and a brief summary of their intended use.

Control Summary
Button A simple push button Control, used in most user interfaces for invoking an action or command when pressed.
CheckBox A simple button Control which displays a check or mark when selected. Commonly used for displaying multiple choices to a user which are not mutually exclusive.
ChoiceBox Specializes in presenting the user a list of choices in a popup or drop-down list from which the user may select at most one item. Especially useful as a non-editable ComboBox with a reasonably small set of choices.
Hyperlink A button Control which looks like a Label and operates much like an anchor tag in HTML. The Hyperlink is not tied to URLs, but rather, can execute any action when clicked.
Label Simple yet powerful Control for displaying text. If the text is too long for the space available, it may be truncated using one of several different overrun styles. May display single or multiple lines of text.
ListView A powerful multi-row control where each row is defined as a Cell. Supports virtually unlimited numbers of rows. Supports dynamically variable non-homogenous row heights. Can be horizontal or vertical.
PasswordBox Simple password entry control with customizable echo strings and optional delay between when a character is typed and when it is masked.
ProgressBar A specialization of the ProgressIndicator which is represented as a horizontal or vertical bar.
ProgressIndicator A circular control which is used for indicating progress, either infinite (aka indeterminate) or finite. Often used with the Task API for representing progress of background Tasks.
RadioButton Typically used with a ToggleGroup as a way of forming a mutually exclusive set of options from which to choose. This is similar in use to a ChoiceBox. The RadioButton is the right choice when the number of options from which to choose is small.
ScrollBar Either a horizontal or vertical bar with increment and decrement buttons and a "thumb" with which the user can interact. Typically not used alone but used for building up more complicated controls such as the ScrollView and ListView.
ScrollView A scrollable viewport within which other Nodes may be placed, such as an ImageView.
Separator A Control used for drawing a horizontal or vertical separator. Typically used in connection with ToolBars or Menus.
Slider A rich and powerful Control for allowing the user to select a value from within a range. The range can be limited to discrete intervals or be high in precision (limited to the range of a Number). The Slider may have an optional set of "tick mark labels" for indicating locations within the slider.
TextBox A single-styled single or multi-lined text input Control. Suitable for most forms of text entry.
ToggleButton A simple button control which may be selected. Can be used with a to form a mutually exclusive set of ToggleButtons. Generally used in favor of RadioButtons when displaying a set of modes to the user (such as panels to view) as opposed to a set of choices the user can chose from.
Tooltip A type of popup which indicates to the user the function of some Control when the Control is hovered over by the mouse.

In addition to the Controls listed here, there are a variety of helper classes and mixins which the UI Controls library uses extensively, such as Labeled, Cell and ToggleGroup. There are also a number of preview controls which are available in the com.javafx.preview.control package. These Controls are not final and will change in future releases. However, they have been made available for early adopters to experiment with in hopes of providing necessary feedback to help make the JavaFX UI Controls library the most powerful and pleasing UI Controls library available.

The remainder of this document will describe the basic architecture of the JavaFX UI Control library, how to style existing controls, write custom skins, and how to use controls to build up more complicated user interfaces.

Architecture

Controls follow the classic MVC design pattern. The Control is the "model". It contains both the state and the functions which manipulate that state. The Control class itself does not know how it is rendered or what the user interaction is. These tasks are delegated to the Skin ("view") and Behavior ("controller") classes respectively.

All Controls extend from the Control class, which is in turn a Parent node, and which is both a Resizable and a TextOffsets (for purposes of baseline alignment). Every Control has a reference to a single Skin, which is the view implementation for the Control. The Control delegates to the Skin the responsibility of computing the min, max, and pref sizes of the Control, the baseline offset, and hit testing (containment and intersection). The Control delegates to the Behavior all handling of key events which occur on the Control when it contains the focus.

Other than these clearly defined points of delegation, there should be no communication from a Control to a Skin or a Behavior. In general, the Control worries only about modifying its own internal state. These state changes may be exposed to the Skin via bindings or layout changes. Rather than having the Control push change notification to the Skin, it is the responsibility of the Skin to observe state changes on the Control by using binding.

Likewise, the Behavior should be decoupled from the Skin such that it does not communicate directly with a Skin. Instead, the Skin calls functions on the behavior in response to input events, and the Behavior then modifies state on the control (typically by invoking some function on the control which mutates the control's state).

Thus, when state on the Model (Control) changes, the View (Skin) is notified via binding and then updates accordingly. When user interaction occurs on the View (Skin), it notifies the Controller (Behavior) which then may mutate state on the Model (Control).

Control

Control extends from Parent, and as such, is not a leaf node. From the perspective of a developer or designer the Control can be thought of as if it were a leaf node in many cases. For example, the developer or designer can consider a Button as if it were a Rectangle or other simple leaf node.

Since it is a Resizable, a Control will be auto-sized to its preferred size on each scenegraph pulse. Setting the width and height of the Control does not affect its preferred size. When used in a layout container, the layout constraints imposed upon the Control (or manually specified on the Control) will determine how it is positioned and sized. In general, any Node in the scenegraph can be given a preferred size by setting LayoutConstraints on the Node. See the javafx.scene.layout package documentation for more information.

The Skin of a Control can be changed at any time. Doing so will mark the Control as needing to be laid out since changing the Skin likely has changed the preferred size of the Control. If no Skin is specified at the time that the Control is created, then a default CSS-based skin will be provied for all of the built-in Controls.

Each Control may have an optional tooltip specified. The Tooltip is a Control which displays some (usually textual) information about the control to the user when the mouse hovers over the Control from some period of time. It can be styled from CSS the same as with other Controls.

focusTraversable is overridden in Control to be true by default, whereas with Node it is false by default. Controls which should not be focusable by default (such as Label) override this to be false. blocksMouse is also overridden in Control to be true by default since users expect most Controls (such as buttons) to consume mouse events. Most Controls therefore will block mouse events from reaching nodes which are rendered behind them in the scene graph.

The getMinWidth, getMinHeight, getPrefWidth, getPrefHeight, getMaxWidth, and getMaxHeight functions are delegated directly to the Skin. The baselineOffset variable is delegated to the node of the skin. It is not recommended that subclasses alter these delegations.

As with all Resizables, the layoutBounds is defined to be based on the width and height of the Resizable. It is not recommended to change this definition in subclasses.

Skin

Skin is the abstract class which represents the "view", or visuals, of a Control. The Control itself is not responsible for its visual representation but instead delegates this to the Skin. The Control contains no visual state. There are a few notable exceptions such as textFill on Label and font on Labeled. Typically, visual state resides solely on a Skin implementation and is set or manipulated from CSS. This design is crucial for allowing for wildly different Skin implementations.

The Skin has a readonly reference to the Control it is currently assigned to. A single Skin instance can be used on one and only one Control at a time. The Skin also maintains a reference to the Behavior associated with that Skin. The behavior variable is readonly, but can be set by Skin subclasses. It is the responsibility of the subclass to specify which Behavior it uses.

Default implementations of the getMinWidth, getMinHeight, getPrefWidth, getPrefHeight, getMaxWidth, and getMaxHeight functions exist in the Skin class. By default, the min width and height is 0, the pref width is 100, the pref height is 50, and the max width and height is Float.MAX_VALUE. While the min and max defaults are reasonable, the pref width and height defaults were chosen so as to be something roughly reasonable (ie: not zero). The rationale was to make it easier to get a basic Skin implementation up and running. However, these defaults hide an error condition. It is the responsibility of a Skin implementation to implement the getPrefWidth and getPrefHeight functions, otherwise the Control will always default to be 100 x 50 (and by virtue of auto-sizing, will be forced to be this size if not given different preferred widths and heights). It would be cleaner to have made these functions abstract. In a subsequent release these may be made abstract. Skin implementations must always override the getPrefWidth and getPrefHeight functions. It is an error in the implementation of the Skin subclass if these functions are not overridden.

Behavior

The last main architectural element is the Behavior class. The Behavior is responsible for implementing the user interaction logic of the Control. For example, the Button's behavior is responsible for handling the press-arm-release semantics used with Buttons. The Control delegates all keystrokes to the Behavior when the Control has the focus. The Skin delegates all mouse events or other input events that it receives to the Behavior so that the behavior may implement the user interaction logic of the Control and modify state on the Control as necessary.

The Behavior API itself is principally comprised of a single function callActionForEvent which is called from the Control whenever a key event occurs on that Control. This function is not abstract, but under normal circumstances a subclass of Behavior will want to override this function and provide an implementation, otherwise keystrokes would not be correctly setup for use for that Control.

Styling Controls

There are two methods for customizing the look of a Control. The most difficult and yet most flexible approach is to write a new Skin for the Control which precisely implements the visuals and behaviors which you desire for the Control. Consult the Skin documentation for more details.

The easiest and yet very powerful method for styling the built in Controls is by using CSS. Please note that in this release the following CSS description applies only to the default Skins provided for the built in Controls. Subsequent releases will make this generally available for any custom third party Controls which desire to take advantage of these CSS capabilities.

Each of the default Skins for the built in Controls is comprised of multiple individually styleable areas or regions. This is much like an HTML page which is made up of <div>'s and then styled from CSS. Each individual region may be drawn with backgrounds, borders, images, padding, margins, and so on. The JavaFX CSS support includes the ability to have multiple backgrounds and borders, and to derive colors. These capabilities make it extremely easy to alter the look of Controls in JavaFX from CSS.

The colors used for drawing the default Skins of the built in Controls are all derived from a base color, an accent color and a background color. Simply by modifying the base color for a Control you can alter the derived gradients and create Buttons or other Controls which visually fit in with the default Skins but visually stand out.


    import javafx.scene.control.Button;

    Button {
        text: "JavaFX"
        style: "base: red"
    }
    

As with all other Nodes in the scenegraph, Controls can be styled by using an external stylesheet, or by specifying the style directly on the Control. Although for examples it is easier to express and understand by specifying the style directly on the Node, it is recommended to use an external stylesheet and use either the styleClass or id of the Control, just as you would use the "class" or id of an HTML element with HTML CSS.

Each UI Control specifies a styleClass which may be used to style controls from an external stylesheet. For example, the Button control is given the "button" CSS style class. The CSS style class names are hyphen-separated lower case as opposed to camel case, otherwise, they are exactly the same. For example, Button is "button", RadioButton is "radio-button", Tooltip is "tooltip" and so on.

If you wish to override an existing style in your stylesheet, you can do so simply by providing the rule you would like to use. For example, if you wanted all Buttons to be red by default, you could do the following:


    .button {
        base: red;
    }
    

If you wish to take complete control of the look of a Control from CSS, then instead of overriding properties you may instead want to give your Control a different styleClass and provide unique styles for it in CSS. For example:


    import javafx.scene.control.Button;

    Button {
        text: "JavaFX"
        styleClass: "my-button"
    }
    

    /* in css stylesheet */
    .my-button {
        background-color: red
    }
    

The class documentation for each Control defines the default Skin regions which can be styled. For further information regarding the CSS capabilities provided with JavaFX, see the CSS Reference Guide.

 
javafx.scene.effect

Provides the set of classes for attaching graphical filter effects to JavaFX Scene Graph Nodes.

Provides the set of classes for attaching graphical filter effects to JavaFX Scene Graph Nodes.

An effect is a graphical algorithm that produces an image, typically as a modification of a source image. An effect can be associated with a scene graph Node by setting the effect attribute. Some effects change the color properties of the source pixels (such as javafx.scene.effect.ColorAdjust), others combine multiple images together (such as Blend), while still others warp or move the pixels of the source image around (such as DisplacementMap or PerspectiveTransform). All effects have at least one input defined and the input can be set to another effect to chain the effects together and combine their results, or it can be left unspecified in which case the effect will operate on a graphical rendering of the node it is attached to.

 
javafx.scene.effect.light

Provides the set of classes for light source implementations needed for the Lighting effect.

Provides the set of classes for light source implementations needed for the Lighting effect.

 
javafx.scene.image

Provides the set of classes for loading and displaying images.

Provides the set of classes for loading and displaying images.

  • The javafx.scene.image.Image class is used to load images (synchronously or asynchronously). Image can be resized as it is loaded and the resizing can be performed with specified filtering quality and with an option of preserving image's original aspect ratio.
  • The javafx.scene.image.ImageView is a Node used for displaying images loaded with Image class. It allows displaying a dynamically scaled and/or cropped view of the source image. The scaling can be performed with specified filtering quality and with an option of preserving image's original aspect ratio.

 
javafx.scene.input

Provides the set of classes for mouse and keyboard input event handling.

Provides the set of classes for mouse and keyboard input event handling.

 
javafx.scene.layout

The JavaFX layout API provides a mechanism to establish the dynamic layout behavior of nodes in the scene graph.

The JavaFX layout API provides a mechanism to establish the dynamic layout behavior of nodes in the scene graph. While parts of an application's scene graph may have a static layout where the size and position of nodes is fixed, other parts will need to be laid out dynamically as the application executes. This is required in part because JavaFX is a cross-platform technology, which means that often the precise size of things (screen, fonts, etc) may vary across platforms and cannot be reliably determined until runtime. The other driver is that modern interfaces are highly dynamic (rotating screens, variable content, etc), so it's impossible for most applications to predict the exact size and location of visual elements over time, especially if the user can resize the screen or nodes within it.

Therefore, layout often requires that the size and position of nodes be defined relative to aspects of the scene graph (scene size, node bounds, etc), often resulting in a complex set of dependencies, particularly in a large scene. These dependencies can be defined by using JavaFX's bind language feature, however, as the scene becomes complex, this approach becomes both unwieldy to program and inefficient to execute. So, the scene graph also supports a procedural layout mechanism that enables branches of the scene graph to be marked as 'needing layout' so that such dirty branches will be laid out in a single top-down procedural layout pass on the next pulse, just prior to rendering. This approach allows layout changes to be coalesced and processed just once, avoiding unnecessary interim layout calculations.

This layout mechanism is driven automatically by the scene graph once the application creates and displays a Scene. An application typically only needs to declare the scene graph structure using appropriate node classes and the scene graph invokes layout at appropriate times.

Laying out a Scene

Applications create a scene graph by placing nodes in the content sequence of a Scene. The portion of the scene graph that will be visible to the user (the 'viewport') is defined by the scene's bounds: 0,0 width x height. By default the scene will not constrain the contents of the scene graph to fit within its bounds, so any nodes which extend beyond its bounds will simply be clipped.

If an application wishes to constrain the contents of the scene graph to fit within the visual bounds of the scene, then it should use a container at the root of the scene and bind the container's width/height to the width/height of the scene:

Stage {
    var scene:Scene;
    scene: scene = Scene {
        width: 500
        height: 400
        contents: Stack {
            width: bind scene.width
            height: bind scene.height
            content: [ ....]
        }
    }
}
This will also ensure that for desktop applications, where the user may resize the stage/scene, that the contents will track those dynamic changes.

For desktop applications, there are two ways to establish the initial size of a scene. First, the application may set the scene's width/height variables directly, as in the above example. Alternatively, the application may leave the scene's width/height uninitialized and allow the scene to compute its own initial size based on the preferred size of its content (e.g. 'packing' the scene around the content):

Stage {
    var scene:Scene;
    scene: scene = Scene {
        // scene will 'shrink-to-fit' its content
        contents: Stack {
            width: bind scene.width
            height: bind scene.height
            content: [ ....]
        }
    }
}
Note that for non-desktop applications (tv, mobile), the size of the stage/scene may be fixed by the device and not configurable by the application.

Resizable vs. Non-Resizable Nodes

The scene graph supports both resizable and non-resizable nodes. A resizable node is one which has a range of acceptable sizes (minimum, preferred, maximum) and its parent will resize it within that range during layout, given the parent's own layout policy and the layout needs of sibling nodes. Applications should therefore not set the width/height of resizable nodes since parents will override those values during layout. See Resizable for more details. Non-resizable nodes, on the other hand, do not have a consistent resizing API and so are not resized by their parents during layout; Applications must establish the size of non-resizable nodes by setting appropriate variables.

Resizable ClassesNon-resizable Classes
Containers, ControlsGroup, CustomNode, Shapes, Text, ImageView

For example:

    Button {
        // Resizable: do NOT set width/height, as parent will resize during layout
        text: "Apply"
    }
    Circle {
        // Non-resizable: must establish shape size by setting geometric variables
        radius: 50
        strokeWidth: 2
    }

Note: Be aware that Rectangle's width/height variables are not the same as Resizable's width/height variables, since for a Rectangle the width/height does not include its stroke, which is centered on its geometry, causing its bounds to extend outside its width/height values.

Using Groups vs. Containers

Group and Container are both general-purpose Parent classes, however each deals with layout differently.

Group is not Resizable and does not constrain its content in any way; it simply takes on the collective bounds of its children. Groups do not position their children, so applications must set the position of nodes inside a group. If a group contains Resizable content, it will auto-size those nodes to their preferred sizes during layout, unless autoSizeChildren is false. The following Group example creates a row of 10 circles:

Group {
    opacity: .5
    content: for (i in [0..9]) {
        def c = Circle {
            radius: 20
            // Must compute position
            layoutX: bind (i * 25) - c.layoutBounds.minX
            layoutY: bind 0 - c.layoutBounds.minY
        }
    }
}

Container classes are Resizable and are designed to perform layout on their children. They will attempt to constrain their contents to fit within their width/height, although it's possible for their content to extend outside their bounds and the container will not clip it. Containers will also layout children regardless of their visibility, so if an application doesn't want an invisible node to be factored into the container's layout, then it should unmanage it (described later).

To compare with the Group example above, let's instead use an HBox container to create the same row of circles:

HBox {
    spacing: 5
    content: for (i in [0..9]) {
        Circle {
            radius: 20
        }
    }
}

As the preceding example shows, it's much easier to use Container classes to achieve common layout patterns, so applications should utilize containers whenever possible and fall back to direct layout inside groups when containers won't suffice or the direct approach is sufficiently simple (e.g. static positioning or minimal bind requirements).

If an application doesn't want a parent (Container, Group, etc) to manage the layout of a node at all, it can unmanage the node:

Stack {
    content: [
        Rectangle {
            managed: false
        }
        ...other content...
     ]
}
Once a node is unmanaged, the application must take full responsibility to manage the size and position of the node, as its parent will completely ignore it in terms of layout. See Node.managed for more details.

Using Concrete Containers

The platform provides a handful of concrete Container classes for common layout idioms:

Container Description
Stack Lays out nodes in a back-to-front layered stack with configurable alignment.
HBox Lays out nodes in single row with configurable spacing and alignment.
VBox Lays out nodes in single column with configurable spacing and alignment.
Tile Lays out nodes in uniformly sized "tiles", where tiles are either flowed horizontally in rows or vertically in columns.
Flow Lays out nodes in either a horizontal or vertical "flow", wrapping nodes at its width (for horizontal) or height (for vertical) boundaries.
Panel Enables layout customization using an object-literal (vs. Container subclass).
ClipView Lays out a single node in a view with a rectangular clip.

Applications often need to nest different containers to achieve desired layout structure. For example, the following code creates a scene with an 8 pixel margin around the edges, a toolbar spanning the top, a tile of images in the center, and a status area at the bottom:

Stage {
    title: "Nested Containers"
    var scene:Scene;
    scene: scene = Scene {
        content: VBox {
            width: bind scene.width
            height: bind scene.height
            padding: Insets { top: 8 right: 8 bottom: 8 left: 8 }
            content: [
                ToolBar { ... }
                Tile {
                    hgap: 6 vgap: 6
                    content: for (img in images)
                                 ImageView { image: img }
                }
                Label { text: "Status:" }
            ]
        }
    }
}

All of the concrete container classes do layout by assigning a "layout area" to each child and then laying out the child within that area using the child's layout preferences for sizing and alignment. If the child is Resizable (Controls and Containers), the container will use its sizing preferences to compute its layout area and determine how to size it within that area. If the child is non-resizable (Shapes, Group, etc), the container will treat it as a rigid object and simply position it within its layout area.

Customizing Layout Preferences

All the concrete container classes support customizing layout preferences on a per-node basis by setting a LayoutInfo on the node's layoutInfo variable. The most common application usage of LayoutInfo is to override the preferred size of a resizable node:

VBox {
    spacing: 8
    content: [
        Label { Text: "Friends" }
        ListView {
            layaoutInfo: LayoutInfo { width: 180 height: 150 }
        }
    ]
}

Understanding Layout Bounds

Node defines a separate layoutBounds variable for the purpose of defining the 'logical' bounds of the node that should be used for layout calculations. LayoutBounds does not necessarily correlate to the visual bounds of a node and it is computed differently depending on the node type:

Node Type Layout Bounds
Shape,ImageView Includes geometric bounds (geometry plus stroke).
Does NOT include effect, clip, or any transforms.
Text logical bounds based on the font height and content width, including white space. can be configured to be tight bounds around chars glyphs by setting boundsType.
Does NOT include effect, clip, or any transforms.
Resizable (All Containers & Controls) always 0,0 width x height, regardless of visual bounds, which might be larger or smaller than layout bounds.
Group,CustomNode Union of all visible childrens' visual bounds (boundsInParent)
Does NOT include effect, clip, or transforms set directly on group/customnode, however DOES include effect, clip, transforms set on individual children (since those are included in the child's boundsInParent). CustomNode subclasses may override layoutBounds.

So for example, if a DropShadow is added to a shape, that shadow will not be factored into the bounds of that shape for layout. Or, if a ScaleTransition is used to pulse the size of a button, that pulse animation will not disturb layout around that button.

 
javafx.scene.media

Provides the set of classes for integrating audio and video into JavaFX Applications.

Provides the set of classes for integrating audio and video into JavaFX Applications. Currently, the primarily used for this package is media playback. There are 3 essential classes in the Media Package: Media, MediaPlayer, and MediaView.

This is an example of a simple media player application:

    import javafx.stage.Stage;
    import javafx.scene.Scene;
    import javafx.scene.media.Media;
    import javafx.scene.media.MediaPlayer;
    import javafx.scene.media.MediaView;


    Stage {
        scene: Scene {
            content: MediaView {
                mediaPlayer: MediaPlayer {
                    media: Media{ source:"file:///media/sample.fxm"}
                }
            }
        }
    }

The Stage contains a Scene, which contains a MediaView object. The MediaView object has a MediaPlayer, which is playing the Media object.

 
javafx.scene.paint

Provides the set of classes for colors and gradients used to fill shapes and backgrounds when rendering the scene graph.

Provides the set of classes for colors and gradients used to fill shapes and backgrounds when rendering the scene graph.

 
javafx.scene.shape

Provides the set of 2D classes for defining and performing operations on objects related to two-dimensional geometry.

Provides the set of 2D classes for defining and performing operations on objects related to two-dimensional geometry.

 
javafx.scene.text

Provides the set of classes for fonts and renderable Text Node.

Provides the set of classes for fonts and renderable Text Node.

 
javafx.scene.transform

Provides the set of convenient classes to perform rotating, scaling, shearing, and translation transformations for Affine objects.

Provides the set of convenient classes to perform rotating, scaling, shearing, and translation transformations for Affine objects.

 
javafx.stage

Provides the top-level container classes for JavaFX scripts.

Provides the top-level container classes for JavaFX scripts.

This package encapsulates the JavaFX graphical script surroundings for the Stage - Scene metaphor, with different capabilites available to the Stage depending on the underlying semantics of the runtime container.

The JavaFX TM Stage interface provides interfaces and classes for the environment and presentation of JavaFX script instantiations. The stage presentation specifics for each JavaFX runtime platform will allow a script to be presented on different platforms with consistent functionality across each runtime.

The main areas of functionality of javafx.stage package include

  1. Stage: Stages are the graphical container for JavaFX script instantiations. Stages are the attributed drawing surface for the JavaFX script.

  2. StageExtension: Each Stage may have one or more StageExtension instances set to provide additional functionality for the script. A StageExtension will only be utilized if the script is running within the profile specific to that StageExtension

  3. AppletStageExtension: When a JavaFX script is running within a browser, the AppletStageExtension is enabled to manage the drag transition from a browser to the desktop. Dragging a Stage out of a browser is supported in the Java TM plugin versions 6u10 and later.

  4. StageStyle: The StageStyle specifies the decoration and visibility semantics of the Stage.

 
javafx.util