Occasionally the requirement arises to call a JavaFX function from within a Java method. I needed to do this yesterday, so I thought I'd take a moment to explain a way to do this in three simple steps:
- Create a Java interface
- Extend the interface with a JavaFX class, implementing any functions defined by the interface
- Obtain a reference to, and call a function of, the JavaFX class defined by the interface
Here are snippets of the code that I created yesterday in the context of the steps listed above:
Create the Java interface
public interface UniverseHandler {
public void onSphereClicked(SphereBranch sphereBranch);
}
Extend the interface with a JavaFX class, implementing any functions defined by the interface
public class WindshieldModel extends UniverseHandler {
...model code omitted...
/**
* This is called when user clicks a sphere on the 3D Canvas
*/
public override function onSphereClicked(sphereBranch:SphereBranch) {
curSphereBranch = sphereBranch;
}
}
Obtain a reference to, and call a function of, the JavaFX class defined by the interface
universeHandler.onSphereClicked(currentSphereBranch);
The universeHandler was passed into the constructor of the Java class.
Thanks again to InteractiveMesh.org for their lightweight 3D canvas and classes that enable JavaFX/Java 3D integration!
Regards,
Jim Weaver
JavaFXpert.com
Note that to instantiate a Java class, you can use the new operator.
Posted by: Tadalafil | July 03, 2010 at 12:59 AM
I created the interface but I don't know how to get a reference to the javafx class in java.
Posted by: cell functions | June 30, 2010 at 01:00 AM
"Hello I am new to javafx and i need some help to call javafx code from java. I created the interface but I don't know how to get a reference to the javafx class in java."
Loic,
To get the reference to the the JavaFX class in Java, I'm passing it to the constructor of the Java class, in this case named WindshieldUniverse:
function foo(): Void {
universe = new WindshieldUniverse(universeHandler);
}
Note that to instantiate a Java class, you can use the new operator.
Thanks,
Jim Weaver
Posted by: Jim Weaver | April 27, 2009 at 08:07 AM
Hello I am new to javafx and i need some help to call javafx code from java.
I created the interface but I don't know how to get a reference to the javafx class in java.
thank you for the help
Main.java
public class Main{
private JavaInterface ji;
public Main() {
//My problem
JavaInterface ji = new ????
}
public static void main(String args[]) {
new Main();
}
}
JavaInterface.java
public interface JavaInterface {
public Object createStage();
}
MyStage.fx
public class MyStage extends JavaInterface {
public override function createStage(): Object{
Stage {
title: "Application title"
width: 250
height: 80
scene: Scene {
content: Text {
font: Font {
size: 24
}
x: 10,
y: 30
content: "Application content"
}
}}}}
Posted by: Loic | April 26, 2009 at 09:35 AM