1 javafx overview

Differences from ReactFX

ReactFX is a popular API to implement reactive patterns with JavaFX using the . However, RxJava uses an and the two are not (directly) compatible with each other.

Although ReactFX has some asynchronous operators like , ReactFX emphasizes synchronous behavior. This means it encourages keeping events on the JavaFX thread. RxJavaFX, which fully embraces RxJava and asynchronous design, can switch between threads and schedulers with ease. As long as subscriptions affecting the UI are observed on the JavaFX thread, you can leverage the powerful operators and libraries of RxJava safely.

If you are heavily dependent on RxJava, asynchronous processing, or do not want your entire reactive codebase to be UI-focused, you will probably want to use RxJavaFX.

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

Стилизация с помощью CSS

В JavaFX с помощью каскадных таблиц стилей (CSS) можно стилизировать интерфейс пользователя. Это просто здорово! Ещё никогда не было так легко настроить внешний вид приложения Java.

В этом учебнике мы создадим тему DarkTheme, вдохновленную Метро-дизайном из Windows 8. Принятые стили для кнопок заимствованы из статьи JMetro — Windows 8 Metro controls on Java, написанной Pedro Duque Vieira.

Знакомство с CSS

Если вы хотите приукрасить внешний вид своего приложение JavaFX, то надо иметь хотя бы начальное представление о том, что такое CSS. Хорошее место для старта — этот учебник по CSS.

Для получения специфической информации об использовании CSS в JavaFX доступны следующие ресурсы:

  • Skinning JavaFX Applications with CSS — учебник от Oracle
  • JavaFX CSS Reference — официальный справочник

Стиль, используемый в JavaFX по умолчанию

Стиль, который используется в JavaFX по умолчанию хранится в файле . Его можно найти в файле , который, в свою очередь, располагается в директории Java .

Разархивируйте его и вы найдете в папке .

Этот стиль всегда применяется по умолчанию для всех приложений JavaFX. Добавляя пользовательские стили мы переопределяем стили из файла .

Подсказка: Для того, чтобы знать какие стили следует переопределить, просмотрите этот файл.

Подключение пользовательских CSS-стилей

Добавьте файл в пакет .

DarkTheme.css

Теперь надо подключить эти стили к нашей сцене. Мы можем сделать это программно, в коде Java, но в этом уроке, чтобы добавить стили в наши fxml-файлы, мы будем использовать Scene Builder:

Подключаем таблицы стилей к файлу RootLayout.fxml

  1. В приложении Scene Builder откройте файл .

  2. Во вкладке Hierarchy выберите корневой контейнер , перейдите на вкладку Properties и укажите файл в роли таблиц стилей.

Подключаем таблицы стилей к файлу PersonEditDialog.fxml

  1. В приложении Scene Builder откройте файл . Во вкладке Hierarchy выберите корневой контейнер , перейдите на вкладку Properties и укажите файл в роли таблиц стилей.

  2. Фон всё ещё белый, поэтому укажите для корневого компонента в классе стиля значение .

  3. Выберите кнопку OK и отметьте свойство Default Button в вкладке Properties. В результате изменится цвет кнопки и она будет использоваться по умолчанию когда пользователь, находясь в окне, будет нажимать клавишу Enter.

Подключаем таблицы стилей к файлу PersonOverview.fxml

  1. В приложении Scene Builder откройте файл . Во вкладке Hierarchy выберите корневой контейнер , перейдите на вкладку Properties и укажите файл в роли таблиц стилей.

  2. Вы сражу должны увидеть некоторые изменения: цвет таблицы и кнопок поменялся на чёрный. Все классы стилей и из файла были применены к таблице и кнопкам. С того момента, как мы переопределили некоторые из стилей в нашем css-файле, новые стили применяются автоматически.

  3. Возможно, вам потребуется изменить размер кнопок для того, чтобы отображался весь текст.

  4. Выберите правый компонент внутри компонента .

  5. Перейдите на вкладку Properties и укажите в классе стиля значение . Теперь фон станет чёрного цвета.

Текстовые метки с другими стилями

Сейчас все текстовые метки с правой стороны имеют одинаковый размер. Для дальнейшей стилизации текстовых меток мы будем использовать уже определённые стили и .

  1. Выберите метку Person Details и добавьте в качестве класса стиля значение .

  2. Для каждой метки в правой колонке (где отображаются фактические данные об адресатах) добавьте в качестве класса стиля значение .

Add a Button and Text

The final two controls required for the application are a control for submitting the data and a control for displaying a message when the user presses the button.

First, create the button and position it on the bottom right, which is a common placement for buttons that perform an action affecting the entire form. The code is in . Add this code before the code for the scene.

Example 2-4 Button

Button btn = new Button("Sign in");
HBox hbBtn = new HBox(10);
hbBtn.setAlignment(Pos.BOTTOM_RIGHT);
hbBtn.getChildren().add(btn);
grid.add(hbBtn, 1, 4);

The first line creates a button named with the label and the second line creates an layout pane named with spacing of pixels. The pane sets an alignment for the button that is different from the alignment applied to the other controls in the grid pane. The property has a value of , which positions a node at the bottom of the space vertically and at the right edge of the space horizontally. The button is added as a child of the pane, and the pane is added to the grid in column 1, row 4.

Now, add a control for displaying the message, as shown in . Add this code before the code for the scene.

Example 2-5 Text

final Text actiontarget = new Text();
        grid.add(actiontarget, 1, 6);

shows the form now. You will not see the text message until you work through the next section of the tutorial, .

JavaFX Installation Instructions

Note:

Only one version of the JavaFX SDK and JavaFX Runtime can be installed at a time. The JavaFX Runtime installer will automatically uninstall previous versions.

Double-click the .exe file of whichever installer you downloaded. If you use a bundled installer, the installers run in the following order:

  • Java Development Kit (JDK)

  • Java Runtime Environment (JRE)

  • JavaFX Software Development Kit (SDK)

  • JavaFX Runtime

The default installation directory for the JavaFX 2.1.1 SDK is C:\Program Files\Oracle\JavaFX 2.1 SDK. See for the directories and contents.

The default installation directory for the JavaFX 2.1.1 Runtime is C:\Program Files\Oracle\JavaFX 2.1 Runtime.

2.6 Getting the Most Out of the Execution Environment

Different execution environments have different specifics, and taking these specifics into account can help to make an application more natural and powerful when run in this execution environment.

One specific could be a unique feature that is not applicable to other environments, for example that applications embedded in a web page can use JavaScript to communicate to the host web page. Another specific could be an important peculiarity such as a presized stage that is provided to a JavaFX application embedded into a web page.

shows an example of using JavaScript to go to a new page:

Example 2-4 Using JavaScript to Go to a New Page

final HostServices services = getHostServices();
JSObject js = services.getWebContext();
js.eval("window.location='http://javafx.com'");

See the following pages for more information and examples:

Availability

The JavaFX APIs are available as a fully integrated feature of the Java SE Runtime Environment (JRE) and the Java Development Kit (JDK ). Because the JDK is available for all major desktop platforms (Windows, Mac OS X, and Linux), JavaFX applications compiled to JDK 7 and later also run on all the major desktop platforms. Support for ARM platforms has also been made available with JavaFX 8. JDK for ARM includes the base, graphics and controls components of JavaFX.

The cross-platform compatibility enables a consistent runtime experience for JavaFX applications developers and users. Oracle ensures synchronized releases and updates on all platforms and offers an extensive support program for companies that run mission-critical applications.

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 The Build Process for JavaFX Applications

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

  • (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

  • 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 and

2.3 Application Package

By default, all of the JavaFX packaging tools generate the following collection of files needed to run the application:

  • An application JAR file (or multiple JAR files for large applications)

  • A JNLP file with a deployment descriptor

    A deployment descriptor is an XML file that describes application components, platform requirements, and launch rules.

  • An HTML file containing JavaScript code to embed or launch JavaFX content from the web page

For the Colorful Circles application from the JavaFX Getting Started tutorials, the basic package consists of these files:

  • ColorfulCircles.jar

  • ColorfulCircles.jnlp

  • ColorfulCircles.html

2.5 User Experience

Users are easily annoyed if they are unable to start an application, do not understand what are the next steps, or perceive the application as slow or hung and for many other reasons.

Default JavaFX packaging takes care of many problem areas including:

  • Ensuring the user has the required JRE and JavaFX installed

  • Auto installing 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

For example, when users do not have JavaFX installed and double-click the JAR file for your application, they see a dialog box explaining that they need to download and install the JavaFX Runtime.

Moreover, developers have a wide range of options on how to tune the experience for their users, such as:

  • Customize the messaging (for example explain to users why they need to install JavaFX Runtime in a language other than English)

  • Show your own splash screen and use a custom loading progress indicator

  • Switch to alternative content if the user’s system is not capable of running JavaFX applications

For example, you could pass the following string as a value of the parameter to add a company logo to the default preloader:

In , the text in bold shows what must be changed in the Ant code used to deploy the ColorfulCircles example.

Example 2-3 Ant Task to Add a Company Logo to the Default Preloader

<fx:deploy width="800" height="600"
        outdir="dist-web" outfile="ColorfulCircles">
    <fx:info title="Colorful Circles"/>
    <fx:application name="Colorful Circles example"
            mainClass="colorfulcircles.ColorfulCircles">
        <fx:param  name="javafx.default.preloader.stylesheet"
            value=".default-preloader 
                { -fx-preloader-graphic: url('http://my.company/logo.gif'); }" />
    </fx:application>
    <fx:resources>
        <fx:fileset dir="dist-web" includes="ColorfulCircles.jar"/>
    </fx:resources>
</fx:deploy> 
 

See the following chapters for more information and examples:

2.4 Packaging Tools

There are three different tools that you can use to package your application:

The HTML page generated by default is a simple test page for your application. It includes sample JavaScript code to launch and embed your application, which you can copy to your own web page. To avoid manual copying, consider using HTML templates for application packaging to insert these code snippets into an existing web page. For more information, see

For more information about JavaFX packaging, see

2.4.1 NetBeans IDE

If you use Netbeans IDE (see the JavaFX Getting Started tutorials for information about how to use JavaFX projects in Netbeans IDE), then it will do most of the work for you. Open Project Properties to specify preferred dimensions for your application scene. Enter 800 for width and 600 for height if you use the Colorful Circles example. Then build the project with Clean and Build. Your application package is generated to the dist folder. Open it in Windows Explorer and try double-clicking the HTML, JNLP, or JAR files.

For more information about packaging and deploying simple JavaFX applications using NetBeans IDE, see the basic deployment page in the Getting Started with JavaFX tutorials.

If you want to package a self-contained application, you need to customize the build.xml script in the NetBeans IDE. For more information, see

2.4.2 Ant Tasks

If you are using another IDE, then you can add JavaFX packaging as a post-build step, using Ant tasks that are included in the JavaFX SDK. shows an Ant package task for Colorful Circles.

When you add the attribute attribute into the Ant task, all possible packages will be created: a standalone application package, one or more self-contained application packages for that platform, and a web deployment package. Installable packages are created based on the third-party software that is available at packaging time. For example, if you have both Inno Setup and WiX on Windows, then you will get three packages: a folder with the application, an .exe installer file, and an .msi installer file. For more information, see A simple Ant task with the attribute is shown in .

Example 2-1 Ant Task to Produce All Packages for the ColorfulCircles Application

<taskdef resource="com/sun/javafx/tools/ant/antlib.xml"      
        uri="javafx:com.sun.javafx.tools.ant"
        classpath="${javafx.sdk.path}/lib/ant-javafx.jar"/>
 
<fx:jar destfile="dist-web/ColorfulCircles.jar">
    <fx:application mainClass="colorfulcircles.ColorfulCircles"/>
    <fileset dir="build/classes/">
        <include name="**"/>
    </fileset>
</fx:jar>
 
<fx:deploy width="800" height="600" outdir="dist-web" 
        outfile="ColorfulCircles" nativeBundles="all">
    <fx:info title="Colorful Circles"/>
    <fx:application name="Colorful Circles example"
            mainClass="colorfulcircles.ColorfulCircles"/>
    <fx:resources>
        <fx:fileset dir="dist-web" includes="ColorfulCircles.jar"/>
    </fx:resources>
</fx:deploy> 

 

Usage

Create a new Maven project, use an existing one like HelloFX, or use an archetype.

The project can be modular or non-modular.

JavaFX dependencies are added as usual:

Add the plugin:

Compile the project:

Run the project:

For modular projects, create and run a custom image:

javafx:run options

The plugin includes by default: , and options.

Optionally, the configuration can be modified with:

  • : The main class, fully qualified name, with or without module name

  • : The current working directory

  • : Skip the execution. Values: false (default), true

  • : File to redirect the process output

  • : A list of VM options passed to the executable.

  • : Arguments separated by space for the executed program

  • : When resolving the module-path, setting this value to true will include the
    dependencies that generate path exceptions in the classpath. By default, the value is false, and these dependencies
    won’t be included.

  • : By default, the plugin will place each dependency either on modulepath or on classpath (based on certain factors).
    When configuration is set, the plugin will place all the dependencies on either modulepath or classpath.

    If set as , a module descriptor is required. All dependencies need to be either modularized or contain an Automatic-Module-Name.

    If set as , a Launcher class (like this one)
    is required to run a JavaFX application. Also, if a module-info descriptor is present, it will be ignored.

    Values: MODULEPATH or CLASSPATH.

Example

The following configuration adds some VM options, and a command line argument:

Note

It is possible to use a local SDK instead of Maven Central.
This is helpful for developers trying to test a local build of OpenJFX.
Since transitive dependencies are not resolved,
all the required jars needs to be added as a separate dependency, like:

javafx:jlink options

The same command line options for can be set:

  • : Strips debug information out. Values: false (default) or true
  • : Strip Java debug attributes out (since Java 13), Values: false (default) or true
  • : Compression level of the resources being used. Values: 0 (default), 1, 2.
  • : Removes the directory in the resulting runtime image. Values: false (default) or true
  • : Removes the directory in the resulting runtime image. Values: false (default) or true
  • : Adds the option to bind services. Values: false (default) or true
  • : Adds the option to ignore signing information. Values: false (default) or true
  • : Adds the verbose option. Values: false (default) or true
  • : Adds a launcher script with the given name.
    • If are defined, these will be passed to the launcher script as vm options.
    • If are defined, these will be passed to the launcher script as command line arguments.
  • : The name of the folder with the resulting runtime image
  • : When set, creates a zip of the resulting runtime image
  • : The executable. It can be a full path or the name of the executable, if it is in the PATH.
  • : When using a local JavaFX SDK, sets the path to the local JavaFX jmods

For instance, with the following configuration:

A custom image can be created and run as:

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

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.

Класс PersonOverviewController

Теперь мы отобразим в нашей таблице некоторые данные. Для этого необходимо создать класс-контроллер для представления .

  1. Создайте новый класс внутри пакета и назовите его . (Мы должны разместить этот класс-контроллер в том же пакете, где находится файл разметки , иначе Scene Builder не сможет его найти.)
  2. Для того, чтобы получить доступ к таблице и меткам представления, мы определим некоторые переменные. Эти переменные и некоторые методы имеют специальную аннотацию . Она необходима для того, чтобы fxml-файл имел доступ к приватным полям и методам. После этого мы настроим наш fxml-файл так, что при его загрузке приложение автоматически заполняло эти переменные данными. Итак, давайте добавим следующий код в наш класс:

Примечание: При импорте пакетов всегда используйте пакет javafx, а НЕ awt или swing!

PersonOverviewController.java
package ch.makery.address.view;

import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import ch.makery.address.MainApp;
import ch.makery.address.model.Person;

public class PersonOverviewController {
    @FXML
    private TableView<Person> personTable;
    @FXML
    private TableColumn<Person, String> firstNameColumn;
    @FXML
    private TableColumn<Person, String> lastNameColumn;

    @FXML
    private Label firstNameLabel;
    @FXML
    private Label lastNameLabel;
    @FXML
    private Label streetLabel;
    @FXML
    private Label postalCodeLabel;
    @FXML
    private Label cityLabel;
    @FXML
    private Label birthdayLabel;

    // Ссылка на главное приложение.
    private MainApp mainApp;

    /**
     * Конструктор.
     * Конструктор вызывается раньше метода initialize().
     */
    public PersonOverviewController() {
    }

    /**
     * Инициализация класса-контроллера. Этот метод вызывается автоматически
     * после того, как fxml-файл будет загружен.
     */
    @FXML
    private void initialize() {
    	// Инициализация таблицы адресатов с двумя столбцами.
        firstNameColumn.setCellValueFactory(cellData -> cellData.getValue().firstNameProperty());
        lastNameColumn.setCellValueFactory(cellData -> cellData.getValue().lastNameProperty());
    }

    /**
     * Вызывается главным приложением, которое даёт на себя ссылку.
     * 
     * @param mainApp
     */
    public void setMainApp(MainApp mainApp) {
        this.mainApp = mainApp;

        // Добавление в таблицу данных из наблюдаемого списка
        personTable.setItems(mainApp.getPersonData());
    }
}

Этот код требует некоторых разъяснений:

  • Все поля и методы, к которым fxml-файлу потребуется доступ, должны быть отмечены аннотацией . Несмотря на то, что это требование предъявляется только для полей и методов с модификатором private, лучше оставить их закрытыми и помечать аннотацией, чем делать публичными!
  • После загрузки fxml-файла автоматически вызывается метод . На этот момент все FXML-поля должны быть инициализированы;
  • Метод определяет, какое поле внутри класса будут использоваться для конкретного столбца в таблице. Стрелка означает, что мы использовали лямбда-выражение из Java 8. (Есть вариант сделать то же самое через PropertyValueFactory, но этот способ нарушает безопасность типов).

В нашем примере для столбцов таблицы мы использовали только значения . Если нам понадобится использовать или , то должен иметь дополнительный метод :

myIntegerColumn.setCellValueFactory(cellData -> 
      cellData.getValue().myIntegerProperty().asObject());

Это добавление необходимо сделать из-за неудачного решения при проектировании JavaFX (для подробностей см. это обсуждение).

Соединение класса MainApp с классом PersonOverviewController

Метод должен быть вызван из класса . Это даст нашему контроллеру доступ к экземпляру , к коллекции записей внутри него и к другим элементам класса. Добавьте в метод две дополнительные строки:

MainApp.java — метод showPersonOverview()
/**
 * Показывает в корневом макете сведения об адресатах.
 */
public void showPersonOverview() {
    try {
        // Загружаем сведения об адресатах.
        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(MainApp.class.getResource("view/PersonOverview.fxml"));
        AnchorPane personOverview = (AnchorPane) loader.load();

        // Помещаем сведения об адресатах в центр корневого макета.
        rootLayout.setCenter(personOverview);

        // Даём контроллеру доступ к главному приложению.
        PersonOverviewController controller = loader.getController();
        controller.setMainApp(this);

    } catch (IOException e) {
        e.printStackTrace();
    }
}

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 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 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:

  • JavaFX Packager tool: command in the 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.

Стили¶

Одним из важных перимуществ JavaFX является

использование каскадных таблиц стилей CSS

Рассмотрим пример приложения с кнопками, стиль которых задается в отдельном файле.

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class ButtonStyleTest extends Application {
    public static void main(String[] args) {
        Application.launch(args);
    }
    @Override
    public void start(Stage stage) {
        Button yesBtn = new Button("Yes");
        Button noBtn = new Button("No");
        Button cancelBtn = new Button("Cancel");
        HBox root = new HBox();
        root.getChildren().addAll(yesBtn, noBtn, cancelBtn);
        Scene scene = new Scene(root);
        // Add a style sheet to the scene
        scene.getStylesheets().add("resources/css/buttonstyles.css");
        stage.setScene(scene);
        stage.setTitle("Styling Buttons");
        stage.show();
    }
}

Содержимое файла buttonstyles.css:

.button {
  -fx-background-color: blue;
  -fx-text-fill: white;
}

Можно задавать стили прямо в коде:

Troubleshooting

Here are some tips for working around problems that are sometimes seen during or following an installation.

  1. If you installed the 64-bit version, you may have problems with applications that run on 32 bits. Note that the 32-bit version is compatible with both 32-bit and 64-bit systems, but the reverse is not true. See the JavaFX Supported System Configurations at

  2. Verify that you have a supported environment. See the JavaFX System Requirements document at

  3. Check the release notes for known issues at

  4. Ensure that the JavaFX Runtime is installed. Go to Control Panel, choose Add/Remove Programs, and verify that JavaFX 2.1.1 appears in the list of installed applications. Note that only one version of JavaFX SDK or Runtime can be installed.

  5. Try running the JavaFX pre-built samples. See .

  6. Check your JDK/JRE installation running a standard Java applet, Web Start application, or standalone JAR application.

  7. If you still have unresolved issues, go to the JavaFX Forum at

Packaging the Application in NetBeans IDE

When you run your application in NetBeans IDE or use the Clean and Build command, your application is packaged for all modes of JavaFX deployment, using options that are set as project properties. By default, applications are packaged into the following files as shown in :

  • A JAR file, which contains the compiled class files and images.

  • A JNLP file, which contains a deployment descriptor for the two web modes (Web Start and embedded in browser).

  • An HTML file, which contains basic code for running both the Web Start application and the embedded application using the Deployment Toolkit.

  • A web-files folder, which contains an offline set of files from the Java Deployment Toolkit to assist with starting up your application. For more information about using the Java Deployment Toolkit in JavaFX applications, see «Deployment in the Browser» at

Figure 6-1 Example of Default Application Packaging

Description of «Figure 6-1 Example of Default Application Packaging»

Optionally, you can package your application as a self-contained application in NetBeans IDE by adding the task shown in to the build.xml file.

Example 6-1 Changes to the build.xml File for Packaging Self-Contained Applications

<project name="ColorfulCircles" default="default" basedir="."
        xmlns:fx="javafx:com.sun.javafx.tools.ant">
    target name="-post-jfx-deploy">
        <fx:deploy width="${javafx.run.width}" height="${javafx.run.height}"
                   nativeBundles="all"
                   outdir="${basedir}/${dist.dir}" outfile="${application.title}">
            <fx:application name="${application.title}"
                            mainClass="${javafx.main.class}"/>
            <fx:resources>
                <fx:fileset dir="${basedir}/${dist.dir}" includes="*.jar"/>
            </fx:resources>
            <fx:info title="${application.title}" vendor="${application.vendor}"/>
        </fx:deploy>
    </target>
</project>

A self-contained application runs similar to the way in which a native application runs. The self-contained application package contains your application, the JRE, the JavaFX runtime, and a platform-specific application launcher. An example of a package is shown in . For additional information, see .

Figure 6-2 Example of a Self-Contained Application Package

Description of «Figure 6-2 Example of a Self-Contained Application Package»

How Do I Deploy a JavaFX Application?

JavaFX applications can be deployed in any of the following execution modes:.

  • Run as a standalone program. The application package is available on a local drive. Launch it by using a Java launcher, such as java , or by double-clicking the application JAR file.

  • Launch from a remote server with Web Start. Click a link in a web page to start the application from a remote web server. Once you have downloaded it, you can also start a Web Start application from a desktop shortcut.

  • Embed in a web page. JavaFX content is embedded in the web page and hosted on a remote web server.

  • Launch as a self-contained application. The application is installed on the local drive and runs as a standalone program using a private copy of Java and JavaFX runtimes. You can launch the application in the same way as other native applications for that operating system, for example by using a desktop shortcut or menu entry.

To deploy a JavaFX application:

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 , create a separate JAR file with the preloader resources, using any of the packaging tools listed below. For more information, see

Usage:

Where to Go from Here

This concludes the basic form tutorial, but you can continue reading the following tutorials on developing JavaFX applications.

  • provides tips on how to add a background image and radically change the style of the text, label, and button in the login form.

  • shows an alternate method for creating the login user interface. FXML is an XML-based language that provides the structure for building a user interface separate from the application logic of your code.

  • Working With Layouts in JavaFX explains the built-in JavaFX layout panes, and tips and tricks for using them.

  • provides information on how to run your application outside NetBeans IDE.

Also try out the JavaFX samples, which you can download from the JDK Demos and Samples section of the Java SE Downloads page at . The Ensemble sample contains examples of layouts and their source code.

Дистрибутивы Java

Существует множество сайтов, предлагающих загрузку Java (читай: JDK), и неясно, «кто что предлагает и с каким лицензированием». Этот раздел проливает свет на это.

Проект OpenJDK

Однако это всего лишь исходный код, а не распространяемая сборка (представьте: ваш файл .zip со скомпилированной командой java для вашей конкретной операционной системы). Теоретически вы и я могли бы создать сборку из этого исходного кода, назвать ее, скажем, MarcoJDK, и начать ее дистрибуцию. Но наш дистрибутив не будет сертифицирован, чтобы можно было называть этот дистрибутив совместимым с Java SE.

И хотя поставщики не могут, скажем, удалить метод из класса String перед созданием новой сборки Java, они могут добавить брэндинг (вay!) или добавить некоторые другие утилиты (например, CLI), которые они считают полезными. Но в остальном исходный код одинаков для всех дистрибутивов Java.

Сборки OpenJDK (от Oracle) и OracleJDK

Один из поставщиков, который создает Java из исходного кода, — это Oracle. Это приводит к двум разным дистрибутивам Java, что поначалу может казаться очень запутанными.

Впрочем все сводится к тому, требуется ли вам коммерческая поддержка (номер телефона) для используемой версии Java.

Полный обзор дистрибутива OpenJDK

Рафаэль Винтерхальтер (Rafael Winterhalter) собрал большой список всех доступных сборок OpenJDK, включая их описания: ОС, архитектуру, окна лицензирования, поддержки и обслуживания.

Оцените статью
Рейтинг автора
5
Материал подготовил
Андрей Измаилов
Наш эксперт
Написано статей
116
Добавить комментарий