Getting Started with JavaFX

11 min read

 

JavaFX 1.2 Application Development Cookbook

Over 60 recipes to create rich Internet applications with many exciting features

  • Easily develop feature-rich internet applications to interact with the user using various built-in components of JavaFX
  • Make your application visually appealing by using various JavaFX classes—ListView, Slider, ProgressBar—to display your content and enhance its look with the help of CSS styling
  • Enhance the look and feel of your application by embedding multimedia components such as images, audio, and video
  • Part of Packt’s Cookbook series: Each recipe is a carefully organized sequence of instructions to complete the task as efficiently as possible

Read more about this book

(For more resources on JavaFX, see here.)

Using javafxc to compile JavaFX code

While it certainly makes it easier to build JavaFX with the support of an IDE (see the NetBeans and Eclipse recipes), it is not a requirement. In some situations, having direct access to the SDK tools is preferred (automated build for instance). This recipe explores the build tools that are shipped with the JavaFX SDK and provides steps to show you how to manually compile your applications.

Getting ready

To use the SDK tools, you will need to download and install the JavaFX SDK. See the recipe Installing the JavaFX SDK, for instructions on how to do it.

How to do it…

Open your favorite text/code editor and type the following code. The full code is available from ch01/source-code/src/hello/HelloJavaFX.fx.

package hello;

import javafx.stage.Stage;
import javafx.scene.Scene
import javafx.scene.text.Text;
import javafx.scene.text.Font;

Stage {
title: "Hello JavaFX"
width: 250
height: 80
scene: Scene {
content: [
Text {
font : Font {size : 16}
x: 10
y: 30
content: "Hello World!"
}
]
}
}

Save the file at location hello/Main.fx.

To compile the file, invoke the JavaFX compiler from the command line from a directory up from the where the file is stored (for this example, it would be executed from the src directory):

javafxc hello/Main.fx

If your compilation command works properly, you will not get any messages back from the compiler. You will, however, see the file HelloJavaFX.class created by the compiler in the hello directory.

If, however, you get a “file not found” error during compilation, ensure that you have properly specified the path to the HelloJavaFX.fx file.

How it works…

The javafxc compiler works in similar ways as your regular Java compiler. It parses and compiles the JavaFX script into Java byte code with the .class extension.

javafxc accepts numerous command-line arguments to control how and what sources get compiled, as shown in the following command:

javafxc [options] [sourcefiles] [@argfiles]

where options are your command-line options, followed by one or more source files, which can be followed by list of argument files. Below are some of the more commonly javafxc arguments:

  • classpath (-cp)—the classpath option specifies the locations (separated by a path separator character) where the compiler can find class files and/or library jar files that are required for building the application.

javafxc -cp .:lib/mylibrary.jar MyClass.fx

  • sourcepath—in more complicated project structure, you can use this option to specify one or more locations where the compiler should search for source file and satisfy source dependencies.
  • javafxc -cp . -sourcepath .:src:src1:src2 MyClass.fx

  • -d—with this option, you can set the target directory where compiled class files are to be stored. The compiler will create the package structure of the class under this directory and place the compiled JavaFX classes accordingly.
  • javafxc -cp . -d build MyClass.fx

  • The @argfiles option lets you specify a file which can contain javafxc command-line arguments. When the compiler is invoked and a @argfile is found, it uses the content of the file as an argument for javafxc. This can help shorten tediously long arguments into short, succinct commands.
  • Assume file cmdargs has the following content:

    -d build
    -cp .:lib/api1.jar:lib/api2.jar:lib/api3.jar
    -sourcepath core/src:components/src:tools/src

    Then you can invoke javafxc as:

    $> javafxc @cmdargs

    See also

    • Installing the JavaFX SDK

    Creating and using JavaFX classes

    JavaFX is an object-oriented scripting language. As such, object types, represented as classes, are part of the basic constructs of the language. This section shows how to declare, initialize, and use JavaFX classes.

    Getting ready

    If you have used other scripting languages such as ActionScript, JavaScript, Python, or PHP, the concepts presented in this section should be familiar. If you have no idea what a class is or what it should be, just remember this: a class is code that represents a logical entity (tree, person, organization, and so on) that you can manipulate programmatically or while using your application. A class usually exposes properties and operations to access the state or behavior of the class.

    How to do it…

    Let’s assume we are building an application for a dealership. You may have a class called Vehicle to represent cars and other type of vehicles processed in the application. The next code example creates the Vehicle class. Refer to ch01/source-code/src/javafx/Vehicle.fx for full listing of the code presented here.

    1. Open your favorite text editor (or fire up your favorite IDE).
    2. Type the following class declaration:
    3. class Vehicle {
      var make;
      var model;
      var color;
      var year;

      function drive () : Void {
      println("You are driving a "
      "{year} {color} {make} {model}!")
      }
      }

    4. Once your class is properly declared, it is now ready to be used. To use the class, add the following (highlighted code) to the file:
    5. class Vehicle {
      ...
      }
      var vehicle = Vehicle {
      year:2010
      color: "Grey"
      make:"Mini"
      model:"Cooper"
      };
      vehicle.drive();

    6. Save the file as Vehicle.fx. Now, from the command-line, compile it with:
    7. $> javafxc Vehicle.fx

      If you are using an IDE, you can simply right, click on the file to run it.

      When the code executes, you should see:

      $> You are driving a 2010 Grey Mini Cooper!

    How it works…

    The previous snippet shows how to declare a class in JavaFX. Albeit a simple class, it shows the basic structure of a JavaFX class. It has properties represented by variables declarations:

    var make;
    var model;
    var color;
    var year;

    and it has a function:

    function drive () : Void {
    println("You are driving a "
    "{year} {color} {make} {model}!")
    }

    which can update the properties and/or modify the behavior (for details on JavaFX functions, see the recipe Creating and Using JavaFX functions). In this example, when the function is invoked on a vehicle object, it causes the object to display information about the vehicle on the console prompt.

    Object literal initialization

    Another aspect of JavaFX class usage is object declaration. JavaFX supports object literal declaration to initialize a new instance of the class. This format lets developers declaratively create a new instance of a class using the class’s literal representation and pass in property literal values directly into the initialization block to the object’s named public properties.

    var vehicle = Vehicle {
    year:2010
    color: "Grey"
    make:"Mini"
    model:"Cooper"
    };

    The previous snippet declares variable vehicle and assigns to it a new instance of the Vehicle class with year = 2010, color = Grey, make = Mini, and model = Cooper. The values that are passed in the literal block overwrite the default values of the named public properties.

    There’s more…

    JavaFX class definition mechanism does not support a constructor as in languages such as Java and C#. However, to allow developers to hook into the life cycle of the object’s instance creation phase, JavaFX exposes a specialized code block called init{} to let developers provide custom code which is executed during object initialization.

    Initialization block

    Code in the init block is executed as one of the final steps of object creation after properties declared in the object literal are initialized. Developers can use this facility to initialize values and initialize resources that the new object will need. To illustrate how this works, the previous code snippet has been modified with an init block. You can get the full listing of the code at ch01/source-code/src/javafx/Vehicle2.fx.

    class Vehicle {
    ...
    init {
    color = "Black";
    }
    function drive () : Void {
    println("You are driving a "
    "{year} {color} {make} {model}!");
    }
    }

    var vehicle = Vehicle {
    year:2010
    make:"Mini"
    model:"Cooper"
    };

    vehicle.drive();

    Notice that the object literal declaration of object vehicle no longer includes the color declaration. Nevertheless, the value of property color will be initialized to Black in the init{} code block during the object’s initialization.

    When you run the application, it should display:

    You are driving a 2010 Black Mini Cooper!

    See also

    • Declaring and using variables in JavaFX
    • Creating and using JavaFX functions

    Creating and using variables in JavaFX

    JavaFX is a statically type-safe and type-strict scripting language. Therefore, variables (and anything which can be assigned to a variable, including functions and expressions) in JavaFX, must be associated with a type, which indicates the expected behavior and representation of the variable. This sections explores how to create, initialize, and update JavaFX variables.

    Getting ready

    Before we look at creating and using variables, it is beneficial to have an understanding of what is meant by data type and be familiar with some common data types such as String, Integer, Float, and Boolean. If you have written code in other scripting languages such as ActionScript, Python, and Ruby, you will find the concepts in this recipe easy to understand.

    How to do it…

    JavaFX provides two ways of declaring variables including the def and the var keywords.

    def X_STEP = 50;
    prntln (X_STEP);
    X_STEP++; // causes error
    var x : Number;
    x = 100;
    ...
    x = x + X_LOC;

    How it works…

    In JavaFX, there are two ways of declaring a variable:

    • def—The def keyword is used to declare and assign constant values. Once a variable is declared with the def keyword and assigned a value, it is not allowed be reassigned a new value.
    • var—The var keyword declares variables which are able to be updated at any point after their declaration.

    There’s more…

    All variables must have an associated type. The type can be declared explicitly or be automatically coerced by the compiler. Unlike Java (similar to ActionScript and Scala), the type of the variable follows the variable’s name separated by a colon.

    var location:String;

    Explicit type declaration

    The following code specifies the type (class) that the variable will receive at runtime:


    var location:String;
    location = "New York";

    The compiler also supports a short-hand notation that combines declaration and initialization.

    var location:String = "New York";

    Implicit coercion

    In this format, the type is left out of the declaration. The compiler automatically converts the variable to the proper type based on the assignment.

    var location;
    location = "New York";

    Variable location will automatically receive a type of String during compilation because the first assignment is a string literal.

    Or, the short-hand version:

    var location = "New York";

    JavaFX types

    Similar to other languages, JavaFX supports a complete set of primitive types as listed:

    • :String—this type represents a collection of characters contained within within quotes (double or single, see following). Unlike Java, the default value for String is empty (“”).
    • “The quick brown fox jumps over the lazy dog” or
      ‘The quick brown fox jumps over the lazy dog’

    • :Number—this is a numeric type that represents all numbers with decimal points. It is backed by the 64-bit double precision floating point Java type. The default value of Number is 0.0.

      0.01234
      100.0
      1.24e12

    • :Integer—this is a numeric type that represents all integral numbers. It is backed by the 32-bit integer Java type. The default value of an Integer is 0.

      -44
      7
      0
      0xFF

    • :Boolean—as the name implies, this type represents the binary value of either true or false.
    • :Duration—this type represent a unit of time. You will encounter its use heavily in animation and other instances where temporal values are needed. The supported units include ms, s, m, and h for millisecond, second, minute, and hour respectively.

      12ms
      4s
      12h
      0.5m

    • :Void—this type indicates that an expression or a function returns no value. Literal representation of Void is null.

    Variable scope

    Variables can have three distinct scopes, which implicitly indicates the access level of the variable when it is being used.

    Script level

    Script variables are defined at any point within the JavaFX script file outside of any code block (including class definition). When a script-level variable is declared, by default it is globally visible within the script and is not accessible from outside the script (without additional access modifiers).

    Instance level

    A variable that is defined at the top-level of a class is referred to as an instance variable. An instance level is visible within the class by the class members and can be accessed by creating an instance of the class.

    Local level

    The least visible scope are local variables. They are declared within code blocks such as functions. They are visible only to members within the block.

    Packt

    Share
    Published by
    Packt

    Recent Posts

    Harnessing Tech for Good to Drive Environmental Impact

    At Packt, we are always on the lookout for innovative startups that are not only…

    2 months ago

    Top life hacks for prepping for your IT certification exam

    I remember deciding to pursue my first IT certification, the CompTIA A+. I had signed…

    3 years ago

    Learn Transformers for Natural Language Processing with Denis Rothman

    Key takeaways The transformer architecture has proved to be revolutionary in outperforming the classical RNN…

    3 years ago

    Learning Essential Linux Commands for Navigating the Shell Effectively

    Once we learn how to deploy an Ubuntu server, how to manage users, and how…

    3 years ago

    Clean Coding in Python with Mariano Anaya

    Key-takeaways:   Clean code isn’t just a nice thing to have or a luxury in software projects; it's a necessity. If we…

    3 years ago

    Exploring Forms in Angular – types, benefits and differences   

    While developing a web application, or setting dynamic pages and meta tags we need to deal with…

    3 years ago