Articles related to JavaFX Script Mike's Weblog

Monday Mar 31, 2008

So far, all of the examples in my previous article about how to use JavaFX objects in Java code expected the object as an input parameter. But what if you want to create a JavaFX object directly? In this article, I will describe a very simple but effective solution.

(Edit: As Mike Azzi pointed out to me (thanks again!), I should have mention, that it is also possible to create JavaFX objects by using the compiled Java classes directly. I plan to cover this later, in a series of articles about what happens during compilation.)

Let's assume we want to create an instance of MyJavaFXClass as it was defined in the previous article. Code sample 1 shows the implementation of the class.

 1 import java.lang.System;
2
3 public class MyJavaFXClass {
4
5 public attribute property: String;
6
7 public function printProperty() {
8 System.out.println (property);
9 }
10 }

Code Sample 1: Definition of MyJavaFXClass

To create an instance of this class in JavaFX Script, we would usually define an object literal. We can do that as well in Java and pass the object literal to the JavaFX-script engine we already encountered in the previous article. The script engine can parse the object literal and return a new instance of the class.

Code sample 2 shows a Java class, which creates an instance of MyJavaFXClass and uses the script engine to call its function printProperty.

 1 import javax.script.ScriptEngineManager;
2 import com.sun.javafx.api.JavaFXScriptEngine;
3
4 public class Main {
5
6 public static void main (String[] args) {
7 ScriptEngineManager manager = new ScriptEngineManager();
8 JavaFXScriptEngine fxEngine =
9 (JavaFXScriptEngine) manager.getEngineByName ("javafx");
10
11 try {
12 Object o = fxEngine.eval
13 ("MyJavaFXClass { property: \"JavaFX class created in Java\" }");
14 fxEngine.invokeMethod (o, "printProperty");
15 } catch (Exception ex) {
16 ex.printStackTrace();
17 }
18 }
19 }

Code Sample 2: Constructing MyJavaFXClass in Java program
 

Comments:

In his blog, Jim Clarke extended the example above to demonstrate, how to retrieve error messages during the compilation. You can find his post here:
http://blogs.sun.com/clarkeman/entry/javafx_scripting_api

Posted by Michael Heinrichs on April 01, 2008 at 05:24 PM CEST #

It is very cool.......
but why is not the ScriptEngine Class usied directly instead of JavaFXScriptEngine

as using java script or JRUBY......
ScriptEngineManager e = new ScriptEngineManager()
ScriptEngine je = e.getEngineByName ("javascript");

Regards.

Posted by Ahmed Al-Hashimi on June 11, 2008 at 12:28 PM CEST #

Post a Comment:
  • HTML Syntax: NOT allowed