Deploying JavaFX Applications

Previous
Next

5 Packaging Basics

This chapter provides an overview of JavaFX packaging and tools.

This page contains the following topics:

5.1 JavaFX Packaging Overview

A properly packaged JavaFX application runs in one or more of the following deployment modes:

  • As a standalone application, using the system Java Runtime

  • As a self-contained standalone application, using a private copy of Java Runtime

  • As a Web Start application

  • Embedded in a web page

By default, JavaFX packaging tools produce a package that includes everything needed to provide a good user experience for various user environments, including:

  • Ensuring that the required Java and JavaFX Runtimes are installed

  • Autodownloading missing dependencies or offering to install them as needed

  • Providing visual feedback to the user while the application is being loaded

  • Showing descriptive error messages

JavaFX application packages work out of the box in multiple execution environments, including:

  • Launching from the command line using the Java launcher

  • Double-clicking the JAR file or self-contained application launcher

  • Embedding the application into a web page

Optionally, JavaFX packaging tools can produce self-contained application packages that simplify redistribution by avoiding dependencies on external software. For more information about self-contained application packages, see Chapter 6, "Self-Contained Application Packaging."

5.2 Base Application Package

The JavaFX application package that is generated by default includes:

  • An executable application JAR file, which contains application code and resources and can be launched by double-clicking the file

  • Additional application JAR and resource files

  • A deployment descriptor for web deployment (kept in the JNLP file)

  • An HTML file containing sample JavaScript code to embed and launch JavaFX content from a web page

Figure 5-1 shows an example of the structure of a base application package. By default, NetBeans IDE will use also include a copy of other support files in the web-files folder, but for production it is recommended that you use a public copy of the dtjava.js file, because it is always up to date.

Figure 5-1 Example of a Package for Web Deployment

Surrounding text describes Figure 5-1 .

5.3 Overview of Packaging Tasks

The build process for JavaFX applications extends the normal build process with several additional steps, as outlined in Figure 5-2.

Figure 5-2 The Build Process for JavaFX Applications

See graphic description link
Description of "Figure 5-2 The Build Process for JavaFX Applications"

New or modified steps are marked with colored arrows and described as follows:

  • (Optional) Convert stylesheets to binary form

    Converts CSS files to binary form to reduce parsing overhead at application runtime.

  • Create JAR

    Packages code and resources needed for the JavaFX application into a JAR file and embeds the utility classes to support autodetection of JavaFX Runtime, launch on double-click, and integration with the preloader JAR, if needed.

    See Section 5.5, "Create the Main Application JAR File."

  • (Optional) Sign the JAR files

    Signing JAR files is needed only when the application requires elevated privileges, such as accessing files on the local file system or accessing nonsecure system properties. Signing is not a new concept, and you can sign the JAR files for your JavaFX application in the same way as you would for Swing/AWT applications.

    JavaFX Runtime supports a new method to sign JAR files that reduces the JAR size overhead for signing, thereby improving the download time.

    See Section 5.6, "Sign the JAR Files."

  • Run the Deploy task

    Assembles the application package for redistribution. By default, the deploy task will generate the base application package, but it can also generate self-contained application packages if requested. See Section 5.7, "Run the Deploy Task or Command" and Chapter 6, "Self-Contained Application Packaging."

5.3.1 JavaFX Packaging Tools

The recommended way to package JavaFX applications is to use a collection of Ant tasks (ant-javafx.jar), provided with the JavaFX SDK and also with JDK 7 Update 6 or later.

NetBeans IDE uses these Ant tasks to package JavaFX projects. Embedded packaging support in NetBeans IDE covers most of the typical use cases. However, if you need something special, you can always tune packaging by adding custom packaging hooks to the build.xml file (for example, as a -post-jar target).

Most of the other popular IDEs can easily use custom Ant build scripts. Other popular build frameworks, for example Maven or Gradle, support integration with Ant also.

The JavaFX SDK and JDK 7 Update 6 or later include a command-line packaging utility, javafxpackager, which can be used for simple packaging tasks. Note that javafxpackager is a convenience utility and does not provide as much flexibility or as many options as Ant tasks.

Table 5-1 summarizes how to accomplish the build steps using the various packaging tools available. Note that javafxpackager also provides a -makeall macro command to create a complete application package for simple applications (for more information, see Chapter 11, "The JavaFX Packager Tool.").

Table 5-1 JavaFX Packaging Tasks and Tools

Task JavaFX Packager Library Ant Task JavaFX Packager Tool Command NetBeans IDE

Convert any CSS files to binary format (See Section 5.4, "Stylesheet Conversion.")

<fx:csstobin>


javafxpackager -createbss

Packaging category in Project Properties

  • Select Binary Encode JavaFX CSS Files check box.

Create a JAR archive (See Section 5.5, "Create the Main Application JAR File.")

<fx:jar>


javafxpackager -createjar

Occurs by default with a Build command, using the configuration in Project Properties.

Sign a JAR archive as one binary object (See Section 5.6, "Sign the JAR Files.")

<fx:signjar>


javafxpackager -signJar

Deployment category in Project Properties

  • Request unrestricted access check box.

  • To attach a certificate, click Edit.

Assemble application package for deployment (See Section 5.7, "Run the Deploy Task or Command") and Chapter 6, "Self-Contained Application Packaging."

<fx:deploy>


javafxpackager -deploy

Base application package is produced by default with a Build command. To produce self-contained applications, see Section 6.3.2, "Basic Build."


5.4 Stylesheet Conversion

Converting stylesheets to binary format is optional but improves application performance. This is especially noticeable on larger CSS files.

To use a binary CSS file, refer to it instead of the CSS file, as shown in Example 5-1:

Example 5-1 Using a Binary Stylesheet

scene.getStylesheets().add(this.getClass().getResource
        ("mystyles.bss").toExternalForm());

Usage:

  • Ant task: Convert CSS Files to Binary

  • JavaFX Packager tool: -createbss command in the javafxpackager reference

  • NetBeans IDE: In the Packaging category of Project Properties, select Binary Encode JavaFX CSS Files.

5.5 Create the Main Application JAR File

In addition to application classes and resources, you can provide the following information when you create the main application JAR file:

  • Platform requirements

  • Required versions of Java Runtime and JavaFX Runtime

  • Any required Java VM arguments

  • The following details about the application:

    • Name of the main application class (Required)

    • Name of preloader class (if there is a preloader)

    • Name of fallback class to use if the platform does not support JavaFX

  • Details about application resources, if applicable

  • Set of class files and other resources included in the JAR file

  • List of auxiliary JAR files needed by the application, including a custom preloader JAR file (if needed)

The use of JavaFX packaging tools to create the main application JAR file is very important for packaging double-clickable jars and self-contained applications. The main application JAR file will include a launcher program that takes care of the bootstrap launch. This also improves launch by:

  • Checking for the JavaFX Runtime

  • Guiding the user through any necessary installations

  • Setting the system proxy for your application


Note:

If you have a preloader, as shown in Figure 5-2, create a separate JAR file with the preloader resources, using any of the packaging tools listed below. For more information, see Chapter 9, "Preloaders."


Usage:

  • Ant task: <fx:jar> Usage Examples

  • JavaFX Packager tool: -createjar command (see the javafxpackager reference)

  • NetBeans IDE: Handled automatically when you specify this information in the project's properties.

5.6 Sign the JAR Files

Before adding code to sign your application, ensure that signing is needed, because it carries a cost of overhead to perform validation and often causes additional dialog boxes to be shown to the end user on application startup. See Section 3.2.4, "Run in Sandbox Unless Signed and Trusted" to find out when an application needs elevated permissions.

If you want to use traditional methods to sign JAR files, consult the Java Tutorial's steps for code signing and the description of the standard Ant signjar task for information about the traditional signing method.

JavaFX also provides a new signing method that helps to reduce the size overhead of signing the JAR file. In this method, you sign the JAR file as one large object instead of signing every JAR entry individually. This saves up to 10 percent of the total JAR size.

To use the new signing method provided by JavaFX, you need the keystore and signing key. See the Java Tutorial on generating keys for instructions.

Usage:

  • Ant task: <fx:signjar> Usage Examples

  • JavaFX Packager tool: -signJar command in the javafxpackager reference

  • NetBeans IDE: Netbeans IDE users enable signing when they request elevated permissions for the application by selecting the Request unrestricted access check box in the project properties. To sign with a specific certificate, click Edit next to the check box.


Note:

All JAR files must be signed or unsigned in the context of a single deployment descriptor file. If you need to mix signed and unsigned JAR files, use an additional <fx:deploy> Ant task to generate an additional deployment descriptor for each JAR file. These additional deployment descriptors are called extension descriptors. Use <fx:resources> to refer to the extension descriptors when the main descriptor is generated. For an example of how to do this, see Using <fx:resources> for Extension Descriptors.


5.7 Run the Deploy Task or Command

A basic redistribution package consists of the following items:

  • The main executable JAR file

  • (Optional) A set of auxiliary JAR files, including a JAR file with preloader code

  • A deployment descriptor, defining how to deploy the application

  • Either a basic HTML file with sample code to embed the application into your own web page or a custom web page that is the result of preprocessing an HTML template

JavaFX packaging tools can also package the application as a self-contained application bundle. This is an opt-in scenario, and it is disabled by default. For more details, see Chapter 6, "Self-Contained Application Packaging."

To assemble the redistributable package, you can use one of the following ways:

  • Ant task: <fx:deploy> Task Usage Examples

  • JavaFX Packager tool: -deploy command in the javafxpackager reference

  • NetBeans IDE: A redistributable package is created every time you build the project. Packaging options are set in the project's properties.

5.7.1 Configure the Deployment Descriptor

The key part of this task is providing information to fill the deployment descriptor for web deployment. This information includes:

  • Entry points: the main application class, preloader class, and other details

    Defined as attributes of the <fx:application> tag.

  • Parameters to be passed to the application

    Defined using <fx:param> and <fx:htmlParam> tags under <fx:application>.

  • The preferred application stage size

    It is crucial to reserve the display area for embedded content.

    Width and height are defined using width and height attributes in the <fx:deploy> tag for Ant tasks, the javafxpackager -deploy command in the javafxpackager tool, or in the Run category of NetBeans project properties.

  • A description of application to be used in any dialog boxes that the user sees during application startup

    Defined using the <fx:info> tag.

  • Platform requirements, including required versions of Java and JavaFX Runtimes and JVM settings

    Defined using the <fx:platform> tag. For an example, see <fx:platform> Parameter to Specify JVM Options.

  • Desktop integration preferences of the application, such as adding a shortcut to the desktop or a reference to the Start menu.

    Defined using the optional <fx:preferences> tag. See <fx:preferences> Usage Examples.

  • Permissions needed to run the application.

    By default web applications run in the sandbox. To request elevated permissions, use the <fx:permissions> tag. Note that in order for permissions to be granted, application JAR files must be signed, and the user must trust the security certificate used for signing. If the application requests elevated permissions but requirements for the user granting permissions are not met, then the application will fail to launch.

5.7.2 Application Resources

Supported application resource files include:

  • JAR files

  • Native JAR files

  • JNLP files

  • Icons

  • License files

  • Data files

Every resource has additional metadata associated with it, such as operating system and architecture for which this resource is applicable, plus a priority preference defining the point in the application lifecycle at which this resource is needed. Careful use of metadata may have a significant impact of the application startup experience. For a list of supported values, see Table 12-8.

All files in the resource set will be copied to the build output folder. However, not all of them are used in all execution modes, as described in the following paragraphs.

Regardless of execution mode, all regular JAR files from the resource set will be added to the application classpath.

Native JAR files and JNLP files are only used for web deployment. Additional JNLP files are typically used to refer to external JNLP extensions or if the application itself is packaged as a set of components. See Using <fx:resources> for Extension Descriptors in the JavaFX Ant Task Reference.

Native JAR files are used to deploy native libraries used by application. Each native JAR file can contain a set of native dynamic libraries and is inherently platform-specific. For more details, see Example 5-11 and Section 5.8.3, "Packaging Complex Applications."

License files are currently applicable to self-contained applications only and are used to add a click-through license to installable packages. See Section 6.4, "Installable Packages."

Data files do not have special semantics, and applications are free to use them for anything. For example if your application needs to bundle a movie file, then you can mark it as "data," and it will be included into the application package.

For further details, see Table 12-8.

5.7.3 Package Custom JavaScript Actions

The Deployment Toolkit provides a set of hooks that can be used to customize the startup behavior when an application is deployed in the browser. Developers must install a callback function to the hook, so it will be utilized by the Deployment Toolkit.

Chapter 7, "Deployment in the Browser" describes in detail what hooks are available and how to use them in the code. However, in order to ensure that they are correctly installed, they also must be specified at packaging time.

To specify callbacks, list them in the <fx:callbacks> tag under <fx:deploy>. Add an <fx:callback> entry for every callback you want to install and specify the name of the hook in the name attribute. The content of the <fx:callback> tag is the JavaScript function to be used. You can use a full function definition or refer to a function defined elsewhere.

Usage:

  • Ant task: <fx:callback> Usage Examples

  • JavaFX Packager tool: See -deploy command in the javafxpackager reference.

  • NetBeans IDE: Add callbacks in the Deployment category of Project Properties. Click the Edit button to the right of Custom JavaScript Actions.

5.7.4 Web Page Templates

By default, JavaFX packaging tools generate a simple web page with a placeholder for the embedded application. You can manually copy code from this generated page to your real web page, but this is error prone and time consuming if you need to do this often.

JavaFX packaging tools also support injecting required code into an existing web page through the use of an input template. This is especially useful when the application is tightly integrated with the web page, for example if the application uses JavaScript to communicate to the web page, or if callbacks are used and their code is kept in the web page itself.

An input template is an HTML file containing markers to be replaced with JavaScript or HTML snippets needed to deploy the JavaFX application on the web page. Example 5-2 shows an example of an input template.

Example 5-2 HTML Input Template

<html>
    <head>
        <title>Host page for JavaFX Application</title>
        #DT.SCRIPT.CODE#
        #DT.EMBED.CODE.ONLOAD#
    </head>
    <body>
        <h1>Embed JavaFX application into existing page</h1>
        <!-- application will be inserted here -->
        <div id="ZZZ"></div>
    </body>
</html>  

#DT.SCRIPT.CODE# and #DT.EMBED.CODE.ONLOAD# are markers that will be substituted with JavaScript and HTML code snippets when the template is processed. Markers have the form of #MARKERNAME# or #MARKERNAME(id)#,

id is the identifier of an application (specified using the id attribute of the <fx:deploy> tag if you are using Ant), and MARKERNAME is the type of the marker. If id is not specified, then MARKER matches any application. For a list of supported markers, see <fx:template> in the Ant task reference.

Templates can be used to deploy multiple applications into the same page. Use the full form of the marker including application ID (an alphanumeric string without spaces) and pass the partially processed template file when packaging each applications to insert.

Example 5-3 shows an example of a template that is used to deploy multiple applications.

Example 5-3 An Input Template Used to Deploy Multiple Applications

<html>
    <head>
        <title>Page with two application</title>
        <script src="#DT.SCRIPT.URL#"></script>
 
        <!-- code to load first app with id 'firstApp'
             (specified as attribute to fx:application) -->
        <!-- #DT.EMBED.CODE.ONLOAD(firstApp)# -->
 
        <!-- code to load first app with id 'secondApp' -->
        <!-- #DT.EMBED.CODE.ONLOAD(secondApp)# --> 
    </head>
    <body>
        <h1>Multiple applications in the same page</h1>
 
        JavaFX app: <br>
        <!-- First app. Ant task need to use "ZZZ_1 as placeholderId -->
        <div id="ZZZ_1"></div>
 
        Another app: <br>
        <!-- Second app. Ant task need to use "ZZZ_2 as placeholderId -->
        <div id="ZZZ_2"></div>
    </body>
  </html>

Example 5-3 demonstrate one useful feature of the JavaFX template processor: the markers can be placed in the HTML comments. If the comment does not contain anything other than marker code, then the comment tags will be removed from the content in the resulting HTML. This keeps the HTML in the template page well formed.

Usage:

  • Ant task: Add a template tag. See <fx:template> Usage Examples.

  • JavaFX Packager tool: -deploy command in the javafxpackager reference

  • NetBeans IDE: Specify the input HTML template file in the Run category of Project Properties.

5.8 Packaging Cookbook

This sections presents several examples for popular deployment tasks.

The examples use Ant APIs, but in most cases the same result can be achieved using the JavaFX Packager tool. See Chapter 12, "JavaFX Ant Tasks" and Chapter 11, "The JavaFX Packager Tool."

5.8.1 Passing Parameters to the Application

JavaFX applications support two types of application parameters: named and unnamed (see the API for Application.Parameters).

Static named parameters can be added to the application package using <fx:param> and unnamed parameters can be added using <fx:argument>. They are applicable to all execution modes including standalone applications.

It is also possible to pass parameters to a JavaFX application from a Web page that hosts it, using <fx:htmlParam>. Prior to JavaFX 2.2, this was only supported for embedded applications. Starting from JavaFX 2.2, <fx:htmlParam> is applicable to Web Start applications also.

Passing parameters from the HTML page is the most useful if parameters are dynamic. To use this technique, we recommend the following approach:

  • Use a web page template (see Section 5.7.4, "Web Page Templates") to provide JavaScript code to prepare dynamic parameters.

  • Pass a JavaScript snippet as a value for <fx:htmlParam> and specify escape="false". Then it will be evaluated at runtime

Example 5-4 shows the use of various parameter types:

Example 5-4 Using Various Parameter Types

<fx:application name="Test" mainClass="tests.Params">
<!-- unnamed parameters -->
    <fx:argument>Arg1</fx:argument>
    <fx:argument>Arg2 with spaces </fx:argument>
 
    <!-- name parameters -->
    <param name="sampleParam" value="Built with ${java.version}"/>
    <param name="noValueParam"/>
 
    <!-- parameters passed from HTML page -->
    <htmlParam name="staticParamFromWebPage"
               value="(new Date()).getTime()"/>
    <htmlParam name="dynamicParamFromWebPage" escape="false"
               value="(new Date()).getTime()"/>
</fx:application> 

5.8.2 Customizing JVM Setup

Does you application need a larger heap size? Do you want to tune garbage collector behavior? Trace class loading?

You can specify required JVM options and set system properties using the <fx:jvmarg> and <fx:property> tags in your Ant task. These tags are applicable for all execution modes except standalone applications. In other words, you always get the default JVM if you double-click the JAR file, but you can tailor the JVM to your requirements if you are running a self-contained application, a Web Start application, or an application embedded into a web page.

If you use any nonsecure JVM options or system properties, the application will need to have elevated permissions. A set of "secure" JVM command-line arguments and system properties is defined in the Java Web Start Developers' Guide.

In Example 5-5, the Ant task will package the application so that, when the application is run, the JVM will be launched with the following arguments:
"-Xmx400 -verbose:jni -Dpurpose=sample"
.

Neither "-verbose:jni" nor purpose are secure, so elevated permissions are required for Web Start and embedded execution modes.

Example 5-5 Specifying Custom JVM Options and Properties in the Ant Task

<fx:platform javafx="2.1+">
    <fx:jvmarg value="-Xmx400m"/>
    <fx:jvmarg value="-verbose:jni"/>
    <fx:property name="purpose" value="sample"/>
</fx:platform> 

5.8.2.1 Specifying User JVM Arguments

If you require a capability to specify user overridable jvm options, use the <fx:jvmuserarg> attribute in <fx:platform>. This attribute explicitly defines an attribute that can be overridden by the user.


Note:

The user overridable arguments are implemented for Ant tasks only.


Example 5-6 Specifying User Overridable Options

            <fx:platform>
              <fx:jvmuserarg name="-Xmx" value="768m" />
            </fx:platform>

In Example 5-6, -Xmx768m is passed as a default value for heap size. The user can override this value in a user configuration file on linux and mac or in the registry on windows. The configuration file and the registry uses the conventions of the Java Preferences API for location and format.

The node for the applications user preferences is based on the application id (or if that hasn't been specified, the fully qualified main class), which is passed as -Dapp.preferences.id to the Application so it can provide a preferences UI if required. The application can access the jvm user options with node -Dapp.preferences.id and key "JVMOptions".

The following examples provide code for overriding the JVM heap size value of 768m to 400m on different platforms.

Example 5-7 Overriding Default Value on Mac

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
"http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>JVMUserOptions</key> <dict> <key>-Xmx</key> <string>400m</string> </dict> </dict> </plist>

Example 5-8 Overriding Default Value on Windows in Registry

Computer\HKEY_CURRENT_USER\Software\JavaSoft\Prefs\com\companyx\appy\/J/V/M/Options
   name: -Xmx
   type: REG_SZ
   data: 400m

Example 5-9 Overriding Default Value on Linux

~/.java/.userPrefs/com/companyx/appy/JVMOptions/prefs.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE map SYSTEM "http://java.sun.com/dtd/preferences.dtd">
<map MAP_XML_VERSION="1.0">
  <entry key="-Xmx" value="400m"/>
</map>

5.8.2.2 Macro Expansion of Application Directory for jvmarg and jvmuserarg

You can provide string substitution to the root of the install directory for parameters passed into the application.

Example 5-10 Substituting Parameters Passed to the Application

<fx:platform>
  <fx:jvmarg value="-Djava.policy.file=$APPDIR/app/whatever.policy"/>
  <fx:jvmuserarg name="-Xmx" value="768m" />
</fx:platform>

5.8.3 Packaging Complex Applications

Real-life applications often have more than just a single JAR artifact. They may have third-party libraries, data files, native code, and so on. For the complex application you may need special packaging tweaks to support different execution modes

There are too many possible scenarios to cover all cases, but here are some guidelines:

  • Mark platform-specific resources accordingly.

  • For the double-clickable JAR file, consider repackaging everything into a single giant JAR file and loading native libraries and data files from inside the JAR.

    Alternatively, if you prefer to have multiple files:

    • Make sure all dependent JAR files are listed in the <fx:resources> tag in the <fx:jar> task that will create the main JAR file.

    • List all data files and libraries in filesets with type="data" to copy them into the output folder.

    • Load native libraries and resources from locations relative to the main JAR file.

    • See the example <fx:jar> Ant Task for a Simple Application in the Ant Task Reference chapter.

  • For self-contained applications:

    • Avoid packaging anything but the main JAR file using <fx:jar>. Multiple embedded launchers can confuse the native launcher.

    • List all dependent JAR files in the <fx:resources> section of <fx:deploy> and <fx:jar> for the main application JAR file.

    • Either use an explicit location relative to the application JAR file to load native libraries, or copy native libraries into the root application folder. (Use type="data" to copy native library files.)

    • See Example 6-5.

  • For Web Start and embedded applications:

    • List all dependent JAR files in the <fx:resources> section of <fx:deploy>.

    • Native libraries should be wrapped into the JAR files for redistribution.

      Use one JAR file per platform. Ensure the JAR files contain native libraries only and that the libraries are all in the top-level folder of the JAR file.

    • See Example 5-11.

Example 5-11 Packaging Native Libraries into JAR Files

<jar destfile="${basedir}/build/native-libs-win-x86.jar"
        basedir="native/windows/x86" includes="*"/>
<jar destfile="${basedir}/build/native-libs-win-x86_64.jar"
        basedir="native/windows/x86_64" includes="*"/>
        ....
 
<!-- sign all jar files --->
<signjar keystore="test.keystore" alias="TestAlias" storepass="xyz123">
    <fx:fileset dir="dist" includes="**/*.jar"/>
</signjar>
 
<!-- assemble package -->
<fx:deploy width="600" height="400"
           outdir="${basedir}/${bundle.outdir}"
           outfile="Demo">
    <fx:info title="Demo app"/>
    <fx:application name="${bundle.name}"
                    mainClass="${javafx.main.class}"/>
    <fx:permissions elevated="true"/>
    <fx:resources>
        <!-- jar files with classes and shared data -->
        <fx:fileset dir="dist" includes="*.jar"/>
        <fx:fileset dir="dist" includes="lib/*.jar"/>
       
        <!-- add native libs for deployment descriptor -->
        <fx:fileset dir="build" type="native"
                os="windows" arch="x86">
                includes="native-libs-win-x86.jar"/>
        </fx:fileset>
        <fx:fileset dir="build" type="native"
                    os="windows" arch="x64"
                    includes="native-libs-win-x86_64.jar"/>
        </fx:fileset>
                    ...
    </fx:resources>
</fx:deploy> 

5.8.4 Publishing an Application that Fills the Browser Window

Prior to JavaFX 2.2, it was not easy to size embedded applications relative to the size of browser window. The width and height attributes of the <fx:deploy> task can only take numeric values, because they are used not just in the generated HTML/Javascript code but also in the deployment descriptor.

In JavaFX 2.2, two new attributes were added to the <fx:deploy> task: embeddedWidth and embeddedHeight. These attributes enable you to specify the size relative to the browser window (for example, as "50%").

These optional embeddedWidth and embeddedHeight attributes are only used for embedded applications, and only in the generated HTML/Javascript code. Also note that width and height values in pixels are still required.

To fill the browser window completely, you must set embeddedWidth and embeddedHeight to "100%". This alone does not produce a perfect result, because scrollbars will be added to the browser window, for the following reasons:

  • The default HTML template has some other content.

  • The default style of HTML tags may reserve space for things like margins.

The resulting web page will appear to be larger than the view area, and therefore the browser will add scrollbars.

The full solution consists of the following steps:

Example 5-12 Packaging

<fx:deploy width="100" height="100"
           embeddedWidth="100%" embeddedHeight="100%"
           outdir="${basedir}/${dist.dir}" outfile="${application.title}">
    <fx:application name="${application.title}"
                    mainClass="${javafx.main.class}"/>
    <fx:template file="${basedir}/web/index_template.html"
                 tofile="${dist.dir}/TestApp.html"/>
    <fx:resources>
        <fx:fileset dir="${basedir}/${dist.dir}" includes="*.jar"/>
    </fx:resources>
    <fx:info title="${application.title}"
             vendor="${application.vendor}"/>
</fx:deploy> 

Example 5-13 Web Page Template (web/index_template.html)

<html>
    <head>
    <!-- This will be replaced with javascript code to embed the application -->
    <!--        #DT.SCRIPT.CODE#-->
    <!--        #DT.EMBED.CODE.ONLOAD#-->
 
    <!-- Reset html styles to ensure these elements do not waste space -->
        <style>
            html, body {
                margin: 0;
            }
        </style>
    </head>
    <body>
    <!-- Application will be added to the div below -->
        <div id='javafx-app-placeholder'></div>
    </body>
</html> 

5.9 Performance Tuning for Web Deployment

There are several options that can be used to improve application launch time for the first and subsequent launches of web applications.


Tip:

While you actively develop an application it is a good idea to disable optimizations to avoid unneeded complexity. Use them at the final packaging stage.


5.9.1 Background Update Check for the Application

Every time a web application starts (Web Start or embedded), a background update check is conducted for whether updates are required. By default, JavaFX applications perform "lazy" update checks in the background while the application runs. This helps to avoid wait time to check for updates when the application starts. If updates are found, then they will be used only after the application restarts. To switch between update modes, use the following mechanisms in the JavaFX packaging tools:

  • Ant task: updatemode attribute of the <fx:deploy> task.

  • JavaFX Packager tool: -updatemode option of the javafxpackager -deploy command in the javafxpackager tool.

  • NetBeans IDE: In the Deployment category of Project Properties, select Check for Application Updates in Background.

5.9.2 Embed the Deployment Descriptor into the Web Page

You can embed the content of the deployment descriptor into the HTML page, which helps to reduce the number of network connections needed to launch the application, as shown in Figure 5-3.

Figure 5-3 Embedding JNLP Content Reduces Network Connections

Description of Figure 5-3 follows
Description of "Figure 5-3 Embedding JNLP Content Reduces Network Connections"

The original JNLP file will be loaded in the background to perform application update checks.

To embed the content of the deployment descriptor:

  • Ant task: embedjnlp attribute of the <fx:deploy> task.

  • JavaFX Packager tool: -embedjnlp option of the javafxpackager -deploy command in the javafxpackager tool.

  • NetBeans IDE: The content is embedded by default.

5.9.3 Embed Signing Certificate into Deployment Descriptor

If the application is signed, then this option embeds into the JNLP file a copy of the details of the certificate used to sign the JAR files. If the user needs to approve permissions, this certificate, followed by a security prompt, is shown while the application JAR files are being loaded, as shown in Figure 5-4.

Figure 5-4 Advantage of Embedding the Certificate in the Deployment Descriptor

Description of Figure 5-4 follows
Description of "Figure 5-4 Advantage of Embedding the Certificate in the Deployment Descriptor"

To use this feature:

  • Ant task: cachecertificates attribute of the <fx:permissions> task.

  • JavaFX Packager tool: -embedCertificates option of the javafxpackager -deploy command in the javafxpackager tool.

5.9.4 Use New JavaFX Signing Method (Signed Applications)

Reducing the JAR file size helps to reduce download time and improve startup time. See Section 5.6, "Sign the JAR Files."

Previous
Next