Java Reference
In-Depth Information
reflection framework is required is when the Java code needs to create a JavaFX
object. The javafx.reflect package is actually written directly in Java and is
safe to use from Java code assuming you are in the main JavaFX thread. The
package javafx.reflect is covered in more detail later in this chapter.
Java Scripting
If you want to run JavaFX script source from your Java program, you need to use
the Java Scripting API. The Java Scripting API, JSR-223, is a standard frame-
work for running a script from Java code. Any scripting language can be used as
long as it is JSR-223 compliant. Some examples of these supported languages
are JavaScript, Groovy, Python, Ruby, and of course JavaFX script.
Basic Scripting Evaluation
The simplest way to accomplish this is to use the javafx.util.FXEvaluator
class. This class is actually a Java class and can be safely used in a Java program.
FXEvaluator has a static method Object eval(String script) that takes a
JavaFX script as a string and returns the JavaFX object created within that script,
if any. To run your application when using scripting, you must include the JavaFX
compiler JAR, javafxc.jar , in your classpath.
Let's start with a simple Hello World example:
import javafx.util.FXEvaluator;
public class Main {
public static void main(String[] args) {
Object fxObj = FXEvaluator.eval(
"println('hello world');");
System.out.println("JavaFX Object = " + fxObj);
}
}
When run, this program produces the following output:
hello world
JavaFX Object = null
The script is just "println('hello world');" and this merely prints to the
console. Because println does not return anything, the returned object is null.
So, let's modify it a bit:
 
 
Search WWH ::




Custom Search