Java Reference
In-Depth Information
" this.name;\n" +
" }\n" +
"}\n"+
"function run( args:String[] ):Void {\n" +
" Student { name:
name as String
\n" +
" age:
age as Integer
};\n" +
"}\n";
Notice that since we will be using
Bindings (SimpleBindings)
rather than the
engine.put()
methods for adding bindings, we need to cast
name
to
String
and
age
to
Integer
within the script.
Next, the Java code compiles the JavaFX script string into a
CompiledScript
object. Then we get the
Student
object by calling
eval()
with the bindings on
the
CompiledScript
. Lastly, we use the resulting
Student
object to invoke the
getName()
function. This is shown in Listing 11.4.
Listing 11.4
Java Code - Java Scripting API Invoking JavaFX Function
CompiledScript compiled = engine.compile(script);
Bindings bindings = new SimpleBindings();
bindings.put("name", "Eric");
bindings.put("age", 25);
Object fxObject =
compiled.eval(bindings);
Object result =
engine.invokeMethod(fxObject,
"getName");
System.out.println("Result = " + result);
This prints out to the console:
Result = Eric
The ScriptEngine method,
invokeMethod
, can also be used to call functions with
arguments and provides a flexible way to manipulate the state of a JavaFX
object. However, it is not possible to directly manipulate JavaFX instance vari-
ables through the Java Scripting API framework.
If you played around with the previous examples, you may have noticed that
some JavaFX compilation errors print out to the console, and some do not. To
overcome this, you need to add a diagnostic handler to collect the errors and then
Search WWH ::
Custom Search