Introduction[]
The following code example will show you how to update a Java object from a JavaFX script.
DataObject.java:
package fxexamples;
public class DataObject {
private String name;
private String address;
private String phone;
private boolean isDirty;
/*Getters and Setters omitted for brevity*/
public void PrintContents() {
System.out.println("Name: " + name);
System.out.println("Address: " + address);
System.out.println("Phone: " + phone);
}
}
FXtoJava.fx:
package fxexamples;
import javafx.ui.*;
import java.lang.System;
import fxexamples.DataObject;
JAVAOBJ:DataObject;
class DataClass {
attribute name:String;
attribute address:String;
attribute phone:String;
}
var data:DataClass = new DataClass();
operation UpdateJavaData(dc:DataClass) {
JAVAOBJ:DataObject.setName(dc.name);
JAVAOBJ:DataObject.setAddress(dc.address);
JAVAOBJ:DataObject.setPhone(dc.phone);
JAVAOBJ:DataObject.PrintContents();
System.out.println("Updated java object");
}
Frame {
title: "FXTimer"
width: 250
height: 200
content: [ Box {
orientation: VERTICAL
content: [ FlowPanel {
content: [ Label {text: "Name"}, TextField { value: bind data.name columns: 10 } ]
}, FlowPanel {
content: [ Label {text: "Address"}, TextField { value: bind data.address columns: 10 } ]
}, FlowPanel {
content: [ Label {text: "Phone"}, TextField { value: bind data.phone columns: 10 } ]
}, Button {
text: "Update Java Data" action: operation() {
UpdateJavaData(data);
}
}]
}]
visible: true
}
RunFX.java:
package fxexamples;
import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.SimpleScriptContext;
import javax.swing.SwingUtilities;
public class RunFX {
public static void main(String[] args) {
final DataObject myObj = new DataObject();
Runnable fxScript = new Runnable() {
public void run() {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
ScriptEngineManager manager = new ScriptEngineManager(loader);
ScriptEngine engine = manager.getEngineByExtension("fx");
Bindings bindings = engine.createBindings();
//Bind the Java Object to the one we'll use in the JavaFX Script
bindings.put("JAVAOBJ:fxexamples.DataObject", myObj);
ScriptContext context = new SimpleScriptContext();
context.setBindings(bindings, ScriptContext.GLOBAL_SCOPE);
context.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
engine.setContext(context);
String script = "import fxexamples.FXtoJava;";
try {
engine.eval(script);
} catch(Exception ex) {
ex.printStackTrace();
}
}
};
SwingUtilities.invokeLater( fxScript );
}
}