Making Your JavaFX Groovy (JavaFX Languages and Markup) Part 1

According to job trends, Groovy is the most popular language that runs on the JVM other than Java.1 This is helped by the fact that Groovy is extremely easy to get started with; other than a few minor differences,2 any Java program is also a valid Groovy application. This makes it very easy for Java developers to start using it, even before they appreciate all the power and convenience that Groovy brings to the Java ecosystem.

Groovy source files compile directly to Java bytecodes and can run anywhere you have a Java Virtual Machine. As a result, you can access any Java libraries directly, including the JavaFX APIs. A well-written Groovy application will almost always be shorter than the equivalent Java version, because of all the conveniences built into the language. Some of the features of the Groovy language that make it attractive as a replacement for Java and JavaFX code include:

• Closures: The most requested feature for the Java language, closures are particularly important for GUI programming, because they make it much simpler to write code that gets called when an event happens.

• Operator Overloading: Groovy lets you overload existing operators or define new ones, which is important for writing a readable DSL.

• Dynamic Typing: Types are optional in Groovy code, which makes it easier to write succinct code.

• Getter/Setter Access: Groovy will automatically convert direct field access to getters and setters, which shortens this very common pattern for accessing Java APIs.


• Named Constructor Parameters: When initializing an object with a constructor, you can also set fields on the class by referring to them by name. This pattern is used quite a bit in our GroovyFX code later.

• Built-In Data Structure Syntax: Many commonly used data structures, such as Lists and Maps, have a built-in syntax in Groovy, which makes it much more convenient to work with them and build them dynamically.

Using JavaFX directly from Groovy is possible; however, you are missing out on a lot of the benefits of Groovy without using a dedicated DSL library, such as GroovyFX. In the next few sections we show you some of the benefits of writing JavaFX code using the Groovy language and GroovyFX library.

Introduction to GroovyFX

GroovyFX is a library for developing JavaFX applications in Groovy that lets you build your application in a more Groovy-like fashion.The main landing page for GroovyFX is on GitHub at the following URL:

http://groovyfx-project.github.com/

Some of the benefits of writing code using GroovyFX, rather than simply coding directly against the JavaFX APIs include:

• Builder Pattern: GroovyFX has Groovy builders for all the major JavaFX classes, making it easy and convenient to declaratively construct a scene graph.

• Property Generation: The JavaFX property pattern for writing your own properties is quite long-winded, but is replaced with a one-line annotation in GroovyFX.

• Timeline DSL: GroovyFX has a convenient short-hand syntax for animation.

• Convenient Bind Syntax: GroovyFX makes creating bindings much more terse and readable than the equivalent Java code.

• API Improvements: A lot of the JavaFX APIs have been tweaked and enhanced to make them easier to use.

To get you started using GroovyFX, we walk you through setting up a small GroovyFX project from scratch. These directions assume that you already have a current Java and JavaFX 2.0 SDK installed on your system. Also, we have chosen to tailor the instructions for the IntelliJ Community Edition, which is a free, open-source IDE with a long track record of excellent Groovy support. There is also Groovy support for Eclipse, NetBeans, and many other IDEs, so if you have a preference for a different IDE, you can easily adapt these instructions to work with your IDE of choice.

To start with, download and install the latest version of IntelliJ IDEA. The community edition comes with Groovy support, so there is no need to purchase the Ultimate Edition. The IntelliJ web site can be found here:

http://www.jetbrains.com/idea

After installing and launching IntelliJ, you need to create a new Java project with Groovy language support enabled. On the landing page you can click "Create New Project," or if you are on a different screen you can get to the same wizard by selecting "New Project…" from the "File" menu. This will present you with the new Project Wizard shown in Figure 10-2.

IntelliJ new project wizard dialog

Figure 10-2. IntelliJ new project wizard dialog

Name your project "HelloGroovyFX," make sure that the project type is set to "Java Module," and then click Next. For the next page of the wizard, you can simply accept the default src folder location and continue, which will take you to the extension screen shown in Figure 10-3.

The Vanishing Circles application demonstrating JavaFX effects, animation, and interaction

Figure 10-3. The Vanishing Circles application demonstrating JavaFX effects, animation, and interaction

This is where you can select and enable Groovy support for your project. Find Groovy from the list on the left and select the checkbox. You also need to configure a Groovy runtime for it to work with on the right-hand pane. If you don’t already have a current Groovy runtime installation, you can grab the latest from the Groovy site:

http://groovyfx-project.github.com/

The binary zip release should work fine. Extract this to a folder on your hard drive, and then go back to IntelliJ and set up the Groovy library by clicking on the "Create." button and selecting the folder to where you just finished extracting Groovy. To complete the project creation, click "Finish" and your new project will be opened in the current window.

We are almost done with the project setup, but are missing the dependent libraries for JavaFX and GroovyFX. To add these in, open the "Project Structure." dialog from the "File" menu, and navigate to the "Modules" section. This lets you configure the project settings in more detail than the new project wizard allows.

Click on the "Dependencies" tab on the right side and the screen shown in Figure 10-4 appears.

Module configuration screen for the HelloGroovyFX project

Figure 10-4. Module configuration screen for the HelloGroovyFX project

In the Dependencies tab you need to configure two additional jar references, both of which are highlighted in the illustration. The first is the GroovyFX jar file, which you can download from the GroovyFX site. Again, the URL for the GroovyFX site is:

http://groovyfx-project.github.com/

The second dependency is the jfxrt.jar, which is in the lib folder of your JavaFX runtime. On the Windows operating system, this is typically located under "Program Files/Oracle/JavaFX/JavaFX 2.0 Runtime/lib" (for 64-bit) or "Program Files (x86)/Oracle/JavaFX/JavaFX 2.0 Runtime/lib" (for 32-bit).

Now to create the HelloGroovyFX application, we need to add a new Groovy script to the project. Right-click on the src directory of your project and choose "New" > "Groovy Script" from the context menu. This pops up a script creation dialog where you can type the name of your script file and click "OK" to create it, as shown in Figure 10-5.

Groovy Class creation dialog

Figure 10-5. Groovy Class creation dialog

Now you are finally ready to get started with some coding. The HelloGroovyFX application is very short, so you can grab the code from the source bundle that comes with the topic, or just type in the code shown in Listing 10-6 yourself.

Listing 10-6. Hello GroovyFX Code

Hello GroovyFX Code

To run the application, simply right-click on the class and choose ‘Run "HelloGroovyFX"’ from the context menu. This gives you the application shown in Figure 10-6.

Output from running the Hello GroovyFX application in IntelliJ

Figure 10-6. Output from running the Hello GroovyFX application in IntelliJ

Congratulations, you have created and run your very first JavaFX application in Groovy! In the next few sections we go into more detail on the features and capabilities of GroovyFX, but remember that anything you can do in JavaFX is possible in GroovyFX, because it wraps the full JavaFX APIs.

Properties in GroovyFX

One of the features that would most benefit UI development in Java with JavaFX is having a notion of first-class, observable properties in the language. Because this does not exist today, the JavaFX team added properties at an API level, which is sufficient, but much more verbose than a native syntax can provide.

Fortunately, with dynamic languages such as Groovy, it is quite easy to add in powerful features including a native property syntax. Groovy already has a built-in notion of simplified getter/setter access, so you can retrieve and store JavaFX properties just as if they were normal variables. For example, to set the width of a Rectangle in Groovy, all you need to write is:

rectangle.width = 500

And this will be automatically translated to a setter call, such as the following.

rectangle.setWidth(500);

The other part of the JavaFX property pattern that is even more tedious is the creation of new properties. To define a new property on your class in the same way that the JavaFX APIs define properties, you need a total of one field and three methods per property. The standard boilerplate for creating a name property on a Person object is shown in Listing 10-7.

Listing 10-7. JavaFX Property Pattern to Create New Properties in Java

JavaFX Property Pattern to Create New Properties in Java

■ Note The above code can be further optimized by checking whether the property has been created in the getName method, and returning null if it has not been created (and thus not initializing the name property).

Although this code is only a bit more verbose than the standard Java property bean pattern, multiply it by the number of properties you need to define in your application, and you have quite a bit of code to maintain and debug when there is something that is not working as expected.

GroovyFX has a very elegant solution to this using a compiler hook for AST transformations. Rather than copying and pasting the property boilerplate each time you want to define a new property, you can simply annotate a variable with the @FXBindable annotation, and GroovyFX will take care of the rest. It generates exactly the same optimized code you would write by hand, but does it behind the scenes during the compile phase so that your source code is not cluttered with the additional logic.

Listing 10-8 shows what the name property would look like in Groovy.

Listing 10-8. JavaFX Property Pattern to Create New Properties in Java

 JavaFX Property Pattern to Create New Properties in Java

The GroovyFX @FXBindable annotation also supports handling the case where a property has a default initialization value:

tmp4775_thumb

And has a convenient shortcut syntax for converting all the variables in a class to properties:

tmp4776_thumb

■ Caution There is a bug in Groovy 1.8.5 that will give you a compiler error when using FXBindable with Dates. If this bug has not been fixed by the time this is published, you can roll back to Groovy 1.8.2 to fix this.

Next post:

Previous post: