Home > Articles > Programming > Java

JavaFX Primer

This chapter is from the book

Expressions and Operators

Block Expression

A block expression is a list of statements that may include variable declarations or other expressions within curly braces. If the last statement is an expression, the value of a block expression is the value of that last expression; otherwise, the block expression does not represent a value. Listing 3.6 shows two block expressions. The first expression evaluates to a number represented by the subtotal value. The second block expression does not evaluate to any value as the last expression is a println() function that is declared as a Void.

Listing 3.6. Block Expressions

// block expression with a value
var total = {
    var subtotal = 0;
    var ndx = 0;
    while(ndx < 100) {
        subtotal += ndx;
        ndx++;
    };
    subtotal; // last expression
};

//block expression without a value
{
    var total = 0;
    var ndx = 0;
    while(ndx < 100) {
        total += ndx;
        ndx++;
    };
    println("Total is {total}");
}

Exception Handling

The throw statement is the same as Java and can only throw a class that extends java.lang.Throwable.

The try/catch/finally expression is the same as Java, but uses the JavaFX syntax:

try {
} catch (e:SomeException) {
} finally {
}

Operators

Table 3.2 contains a list of the operators used in JavaFX. The priority column indicates the operator evaluation precedence, with higher precedence operators in the first rows. Operators with the same precedence level are evaluated equally. Assignment operators are evaluated right to left, whereas all others are evaluated left to right. Parentheses may be used to alter this default evaluation order.

Table 3.2. Operators

Priority

Operator

Meaning

1

++/-- (Suffixed)

Post-increment/decrement assignment

2

++/-- (Prefixed)

Pre-increment/decrement assignment

-

Unary minus

not

Logical complement; inverts value of a Boolean

sizeof

Size of a sequence

reverse

Reverse sequence order

indexof

Index of a sequence element

3

/, *, mod

Arithmetic operators

4

+, -

Arithmetic operators

5

==, !=

Comparison operators (Note: all comparisons are similar to isEquals() in Java)

<, <=, >, >=

Numeric comparison operators

6

instanceof, as

Type operators

7

and

Logical AND

8

or

Logical OR

9

+=, -=, *=, /=

Compound assignment

10

=>, tween

Animation interpolation operators

11

=

Assignment

Conditional Expressions

if/else

if is similar to if as defined in other languages. First, a condition is evaluated and if true, the expression block is evaluated. Otherwise, if an else expression block is provided, that expression block is evaluated.

if (date == today) {
      println("Date is today");
}else {
      println("Out of date!!!");
}

One important feature of if/else is that each expression block may evaluate to an expression that may be assigned to a variable:

var outOfDateMessage = if(date==today) "Date is today"
                                  else "Out of Date";

Also the expression blocks can be more complex than simple expressions. Listing 3.7 shows a complex assignment using an if/else statement to assign the value to outOfDateMessage.

Listing 3.7. Complex Assignment Using if/else Expression

var outOfDateMessage = if(date==today) {
         var total = 0;
         for(item in items) {
            total += items.price;
         }
         totalPrice += total;
         "Date is today";
    } else {
         errorFlag = true;
         "Out of Date";
 };

In the previous example, the last expression in the block, the error message string literal, is the object that is assigned to the variable. This can be any JavaFX Object, including numbers.

Because the if/else is an expression block, it can be used with another if/else statement. For example:

var taxBracket = if(income < 8025.0) 0.10
       else if(income < 32550.0)0.15
       else if (income < 78850.0) 0.25
       else if (income < 164550.0) 0.28
       else 0.33;

Looping Expressions

For

for loops are used with sequences and allow you to iterate over the members of a sequence.

var daysOfWeek : String[] =
                   [ "Sunday", "Monday", "Tuesday" ];
for(day in daysOfWeek) {
      println("{indexof day}). {day}");
}

To be similar with traditional for loops that iterate over a count, use an integer sequence range defined within square brackets.

for( i in [0..100]} {

The for expression can also return a new sequence. For each iteration, if the expression block executed evaluates to an Object, that Object is inserted into a new sequence returned by the for expression. For example, in the following for expression, a new Text node is created with each iteration of the day of the week. The overall for expression returns a new sequence containing Text graphical elements, one for each day of the week.

var textNodes: Text[] = for( day in daysOfWeek) {
    Text {content: day };
}

Another feature of the for expression is that it can do nested loops. Listing 3.8 shows an example of using nested loops.

Listing 3.8. Nested For Loop

class Course {
    var title: String;
    var students: String[];
}
var courses = [
    Course {
        title: "Geometry I"
        students: [ "Clarke, "Connors", "Bruno" ]
    },
    Course {
        title: "Geometry II"
        students: [ "Clarke, "Connors", ]
    },
    Course {
        title: "Algebra I"
        students: [ "Connors", "Bruno" ]
    },
];

for(course in courses, student in course.students) {
   println("Student: {student} is in course {course}");
}

This prints out:

Student: Clarke is in course Geometry I
Student: Connors is in course Geometry I
Student: Bruno is in course Geometry I
Student: Clarke is in course Geometry II
Student: Connors is in course Geometry II
Student: Connors is in course Algebra I
Student: Bruno is in course Algebra I

There may be zero or more secondary loops and they are separated from the previous ones by a comma, and may reference any element from the previous loops.

You can also include a where clause on the sequence to limit the iteration to only those elements where the where clause evaluates to true:

var evenNumbers = for( i in [0..1000] where i mod 2 == 0 ) i;

while

The while loop works similar to the while loop as seen in other languages:

var ndx = 0;
while ( ndx < 100) {
    println("{ndx}");
    ndx++;
}

Note that unlike the JavaFX for loop, the while loop does not return any expression, so it cannot be used to create a sequence.

Break/Continue

break and continue control loop iterations. break is used to quit the loop altogether. It causes all the looping to stop from that point. On the other hand, continue just causes the current iteration to stop, and the loop resumes with the next iteration. Listing 3.9 demonstrates how these are used.

Listing 3.9. Break/Continue

for(student in students) {
   if(student.name == "Jim") {
      foundStudent = student;
      break; // stops the loop altogether,
             //no more students are checked
   }
}

for(book in Books ) {
      if(book.publisher == "Addison Wesley") {
         insert book into bookList;
         continue; // moves on to check next book.
      }
      insert book into otherBookList;
      otherPrice += book.price;
}

Type Operators

The instanceof operator allows you to test the class type of an object, whereas the as operator allows you to cast an object to another class. One way this is useful is to cast a generalized object to a more specific class in order to perform a function from that more specialized class. Of course, the object must inherently be that kind of class, and that is where the instanceof operator is useful to test if the object is indeed that kind of class. If you try to cast an object to a class that that object does not inherit from, you will get an exception.

In the following listing, the printLower() function will translate a string to lowercase, but for other types of objects, it will just print it as is. First, the generic object is tested to see if it is a String. If it is, the object is cast to a String using the as operator, and then the String’s toLowerCase() method is used to convert the output to all lowercase. Listing 3.10 illustrates the use of the instanceof and as operators.

Listing 3.10. Type Operators

function printLower(object: Object ) {
    if(object instanceof String) {
        var str = object as String;
        println(str.toLowerCase());
    }else { 
        println(object);
    }

}
printLower("Rich Internet Application");
printLower(3.14);

Accessing Command-Line Arguments

For a pure script that does not declare exported classes, variables, or functions, the command-line arguments can be retrieved using the javafx.lang.FX.getArguments():String[] function. This returns a Sequence of Strings that contains the arguments passed to the script when it started. There is a another version of this for use in other invocations, such as applets, where the arguments are passed using name value pairs, javafx.lang.FX.getArguments(key:String):String[]. Similarly, there is a function to get system properties, javafx.lang.FX.getProperty(key:String):String[].

If the script contains any exported classes, variables, or functions, arguments are obtained by defining a special run function at the script level.

public function run(args:String[] ) {
      for(arg in args) {
            println("{arg}");
      }
}

Built-in Functions and Variables

There are a set of functions that are automatically available to all JavaFX scripts. These functions are defined in javafx.lang.Builtins.

You have already seen one of these, println(). Println() takes an object argument and prints it out to the console, one line at a time. It is similar to the Java method, System.out.println(). Its companion function is print(). Print() prints out its argument but without a new line. The argument’s toString() method is invoked to print out a string.

println("This is printed on a single line");
print("This is printed without a new line");

Another function from javafx.lang.Builtins is isInitialized(). This method takes a JavaFX object and indicates whether the object has been completely initialized. It is useful in variable triggers to determine the current state of the object during initialization. There may be times that you want to execute some functionality only after the object has passed the initialization stage. For example, Listing 3.11 shows the built-in, isInitialized() being used in an on replace trigger.

Listing 3.11. isInitialized()

public class Test {
    public var status: Number on replace {
       // will not be initialized
       // until status is assigned a value
        if(isInitialized(status)) {

             commenceTest(status);
        }
    }
    public function commenceTest(status:Number) : Void {
        println("commenceTest status = {status}:);
   }
}

In this example, when the class, Test, is first instantiated, the instance variable, status, first takes on the default value of 0.0, and then the on replace expression block is evaluated. However, this leaves the status in the uninitialized state. Only when a value is assigned to status, will the state change to initialized. Consider the following:

var test = Test{}; // status is uninitialized
test.status = 1; // now status becomes initialized

In this case when Test is created using the object literal, Test{}, status takes on the default value of 0.0; however, it is not initialized, so commenceTest will not be invoked during object creation. Now when we assign a value to status, the state changes to initialized, so commenceTest is now invoked. Please note that if we had assigned a default value to status, even if that value is 0, then status immediately is set to initialized. The following example demonstrates this.

public class Test {
    public var status: Number = 0 on replace {
        // will be initialized immediately.
        if(isInitialized(status)) {
             commenceTest(status);
        }
    }

The last built-in function is isSameObject(). isSameObject() indicates if the two arguments actually are the same instance. This is opposed to the == operator. In JavaFX, the == operator determines whether two objects are considered equal, but that does not mean they are the same instance. The == operator is similar to the Java function isEquals(), whereas JavaFX isSameObject is similar to the Java == operator. A little confusing if your background is Java!

The built-in variables are __DIR__ and __FILE__. __FILE__ holds the resource URL string for the containing JavaFX class. __DIR__ holds the resource URL string for directory that contains the current class. For example,

println("DIR = {__DIR__}");
println("FILE = {__FILE__}");
// to locate an image
var image = Image { url: "{__DIR__}images/foo.jpeg" };

The following examples show the output from a directory based classpath versus using a JAR-based class path.

Using a Jar file in classpath
$javafx -cp Misc.jar misc.Test


DIR = jar:file:/export/home/jclarke/Documents/
     Book/FX/code/Chapter3/Misc/dist/Misc.jar!/misc/


FILE = jar:file:/export/home/jclarke/Documents/
  Book/FX/code/Chapter3/Misc/dist/Misc.jar!/misc/Test.class

Using directory classpath
$ javafx -cp . misc.Test

DIR = file:/export/home/jclarke/Documents/Book/
      FX/code/Chapter3/Misc/dist/tmp/misc/


FILE = file:/export/home/jclarke/Documents/Book/
      FX/code/Chapter3/Misc/dist/tmp/misc/Test.class

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020