Geertjan is a DZone Zone Leader and has posted 468 posts at DZone. You can read more from them at their website. View Full User Profile

Calling JavaFX From Java?

12.09.2008
| 32398 views |
  • submit to reddit

While experimenting with JavaFX, remember that Java is never far away.

In this case, let's call out to Jim Weaver's JavaFX Calculator demo:

Here we go, here's all that's needed, via the Scripting API, which is included in the JavaFX SDK:

package calc;

import java.io.InputStreamReader;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class CalculatorLauncher {

public static void main(String[] args) {
try {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByExtension("fx");
InputStreamReader reader = new InputStreamReader(CalculatorLauncher.class.getResourceAsStream("Calculator.fx"));
engine.eval(reader);
} catch (ScriptException ex) {
}
}

}
And so, here's my whole application, calling Jim Weaver's Calculator demo:

Nice. Even better would be to be able to embed that JavaFX Stage (or a panel-like part thereof?) into a JFrame. Then one would have the best of both worlds: the graphic "oomph" of JavaFX, together with the daily low level grunt work of Java. That, I believe (and hope), is the promise of JavaFX for Java developers (and Groovy developers), as opposed to designers and similar graphic artists, who seem to be the primary target of JavaFX.

AttachmentSize
fig-1.png6.73 KB
fig-2.png14.73 KB
Published at DZone with permission of its author, Geertjan Wielenga.

Comments

steven yi replied on Tue, 2008/12/09 - 8:32pm

Thanks Geertjan for your post!  I think you hit the nail right on the head about embedding JavaFX into Swing applications.  I was a Flash developer from 2000-2006 and I saw it go from "let's build the entire site in Flash", which was often cumbersome to maintain and update, to "let's build a rich media piece in Flash", to which Flash then really came back and excelled (of course, the inclusion of video and broadband was a part of this too). I feel like most of the people who are complaining about the value of JavaFX are basically reliving the same issues that happened when Flash became very popular.  (Note: Been doing Java/Swing since 2000 as well, in case the note above about Flash implies I've been using Java client stuff for just the past couple years).

Andres Almiray replied on Wed, 2008/12/10 - 12:33am

Alex Ruiz replied on Wed, 2008/12/10 - 12:49am

Geertjan,

I can only say...THANK YOU! I was trying to make FEST test a JavaFX UI, but I have been procrastinating for many days! :)

 

Best regards,

-Alex

Peter Koželj replied on Wed, 2008/12/10 - 1:50am

I found an unoffical way to put JavaFx node into swing component tree.

Fx nodes have a function impl_getSGAbstractShape() that can be used
with com.sun.scenario.scenegraph.JSGPanel

I haven't had the time to investigate this further (input handling and resizing),
but I imagine that it should be managable.

Regards,
Peter

Carl Dea replied on Wed, 2008/12/10 - 2:01am

Geertjan,

 

Nice!

One of my questions ultimately answered!

 

Thanks,

Carl

Michael Bien replied on Wed, 2008/12/10 - 4:15am

calling javafx script with the generic script engine api works of course but it feels like calling methods via reflection all the time (regarding boiler plate, compile- vs runetime erros etc..).

I see this approach currently as workaround until we have a official way to instanciate javafx objects in java. JavaFX IS already bytecode, it is even 100% java if you decompile it. So why is there no official way to instantiate JFX objects? I really can't understand that.

Isn't this the first thing you should think about - I mean how are the JFX devs unit testing the apis? How to bind a javafx gui against a plain java bean model? Why rolling out a domain specific language without a easy way to communicate with other domains?

time will show...

Geertjan Wielenga replied on Wed, 2008/12/10 - 4:57am

Thanks all for the comments: good to see I'm not alone in yearning for the marriage of JavaFX with Java! I agree with Michael Bien that it feels like reflection, i.e., some kind of workaround, though. On the (very!) bright side, I received an e-mail from Josh Marinacci with these words: "I'm in belgium and have forgotten my login so i couldn't comment on your blog. Can you post an update that soon we'll have some code that shows you how to properly embed a javafx scene into a swing application."

Michael Bien replied on Wed, 2008/12/10 - 5:26am in response to: Geertjan Wielenga

 thanks for the update geertjan,

[quote=geertjan]On the (very!) bright side... [/quote]

there is a song http://en.wikipedia.org/wiki/Each_Small_Candle from Roger Waters with the text "And each small candle Lights a corner of the dark..."

lets hope we have enough of them for each corner case ;)

steven yi replied on Wed, 2008/12/10 - 11:42am in response to: Geertjan Wielenga

Great news!  Looking forward to seeing the examples!

Alex Ruiz replied on Wed, 2008/12/10 - 12:29pm

Hi Geertjan,

Where can I find the Netbeans project you used in the article? I'm trying to duplicate what you have done without success :(

Many thanks in advance,

-Alex

Geertjan Wielenga replied on Wed, 2008/12/10 - 12:43pm

Hi Alex, you need to put a whole bunch of JavaFX JARs on your app's classpath to make it possible. (To save time, I simply put all of them there, i.e., every JAR in the JavaFX distro.) Then put Jim's FX file in a package and the Java class you see above there too.

Alex Ruiz replied on Wed, 2008/12/10 - 12:53pm

Thanks Geertjan! I tought I had all the JavaFX jars, but I was missing some (I just included the whole JavaFX world!)

Funny thing is that it doesn't work for me all the time. Sometimes I see the calculator, some other times the program is just hanging there doing nothing (no calculator and no exceptions thrown.)

I'll keep trying :)

-Alex

Carl Dea replied on Wed, 2008/12/10 - 11:10pm in response to: Alex Ruiz

Alex,

I called mine Main.class instead.

I was getting the same thing. I figured it had to do with EDT. This works all the time.

Enjoy!


package javatalkingtofx;

import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.swing.SwingUtilities;

public class Main {

public static void main(String[] args) {

ScriptEngineManager manager = new ScriptEngineManager();
final ScriptEngine engine = manager.getEngineByExtension("fx");
final InputStreamReader reader = new InputStreamReader(Main.class.getResourceAsStream("Calculator.fx"));
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
engine.eval(reader);
} catch (ScriptException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
});

}

}

-Carl

Alex Ruiz replied on Thu, 2008/12/11 - 12:00am

Awesome Carl! It works!

Many thanks! :)

-Alex

Alex Ruiz replied on Thu, 2008/12/11 - 4:25am

I wrote about my experience trying to test a JavaFX UI at http://www.jroller.com/alexRuiz/entry/using_fest_swing_to_discover

Best regards,
-Alex

Carl Dea replied on Thu, 2008/12/11 - 10:32am in response to: Alex Ruiz

Alex,

 

Man, all the excitement about JavaFX and I didn't stop to think about testing! Your blog is sobering relating to Java Swing & FEST. I think we should ask the the JavaFX experts about GUI testing workflow.

GUI Designer --> Developer --> Gui Developer/Tester(Unit testing panels)

 

JavaFX Fest version? 

(I didn't know you are one of the developers of FEST, excellent tool!)

 

Thanks!

-Carl

Alex Ruiz replied on Thu, 2008/12/11 - 12:00pm

Thanks Carl for the kind words about FEST :)

About a JavaFX version of FEST, I'm thinking about it. I'd like to release version 1.0 of the FEST-Swing (planned for mid-January 09) and also learn more about JavaFX before announcing anything :)

I followed your suggestion and posted a message in the JavaPosse mailing list (there is a lot of JavaFX-related activity there.) The message can be found at http://groups.google.com/group/javaposse/browse_frm/thread/db150b394d189185?hl=en

Cheers,

-Alex

Cyril Ronseaux replied on Wed, 2008/12/17 - 12:55pm

Hi,

What is the point of launching a JavaFX script from Java, if I don't get interaction. I mean, how can I :

start a java program, that read some configuration from disk, connect to a database, and display data to user in an FX beautiful panel. Then the user clicks a few buttons and inputs a few forms, and the java code is called back.

The piece of code you suggest looks like a System.exec("calc"); In that I mean, having Java and FX exchange data will be great pain... full of workarounds, unstable untestable and unmaintable code, etc.

I seriously hope Sun works load more on that kind of integration : how to replace Swing (or beautify Swing components) with wonderful JavaFX features, yet remaining a Java Application (and ultimatly Java WebStart N-Tiers application !).

I can't wait for the future :)

 

Peter Ojambo replied on Tue, 2010/03/30 - 6:04am in response to: Carl Dea

guyz i have failed to call a JavaFX class from a swing application when a button is clicked.

I developed the application so that when i run the swing application i click a button "Run FX" and the JavaFx class "Main.fx" runs. but all in vain. the error it brings is displayed down below.

My code is shown below.

Please help as soon as possible. probably as soon as u read this message.

// JavaFx Class

/*
* Main.fx
*
* Created on Mar 30, 2010, 11:26:22 AM
*/

package calc;

import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.text.Text;
import javafx.scene.text.Font;

/**
* @author peter
*/

Stage {
title: "Sample app"
scene: Scene {
width: 250
height: 80
content: [
Text {
font : Font {
size : 16
}
x: 10
y: 30
content: "Testing files"
}
]
}
}

 

 

// my swing class


/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

/*
* NewJFrame.java
*
* Created on Mar 30, 2010, 12:02:35 PM
*/

package calc;

import com.sun.javafx.runtime.Main;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.swing.SwingUtilities;

/**
*
* @author peter
*/
public class NewJFrame extends javax.swing.JFrame {

/** Creates new form NewJFrame */
public NewJFrame() {
initComponents();
}

/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
// </editor-fold>

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
ScriptEngineManager manager = new ScriptEngineManager();
final ScriptEngine engine = manager.getEngineByExtension("fx");
final InputStreamReader reader = new InputStreamReader(NewJFrame.class.getResourceAsStream("Main.fx"));
SwingUtilities.invokeLater(new Runnable() {

@Override
public void run() {
try {
engine.eval(reader);
} catch (ScriptException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}

/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new NewJFrame().setVisible(true);
}
});
}

// Variables declaration - do not modify
private javax.swing.JButton jButton1;
// End of variables declaration

}

 

 

 when i click the button "Run FX" it brings the following error

init:
deps-jar:
compile:
jar:
standard-run:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
        at java.io.Reader.<init>(Reader.java:61)
        at java.io.InputStreamReader.<init>(InputStreamReader.java:55)
        at calc.NewJFrame.jButton1ActionPerformed(NewJFrame.java:78)
        at calc.NewJFrame.access$000(NewJFrame.java:27)
        at calc.NewJFrame$1.actionPerformed(NewJFrame.java:50)
        at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
        at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
        at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
        at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
        at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
        at java.awt.Component.processMouseEvent(Component.java:6263)
        at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
        at java.awt.Component.processEvent(Component.java:6028)
        at java.awt.Container.processEvent(Container.java:2041)
        at java.awt.Component.dispatchEventImpl(Component.java:4630)
        at java.awt.Container.dispatchEventImpl(Container.java:2099)
        at java.awt.Component.dispatchEvent(Component.java:4460)
        at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4574)
        at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238)
        at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
        at java.awt.Container.dispatchEventImpl(Container.java:2085)
        at java.awt.Window.dispatchEventImpl(Window.java:2478)
        at java.awt.Component.dispatchEvent(Component.java:4460)
        at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
        at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
        at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
        at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
        at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
browser-run:
jws-run:
midp-run:
run:
BUILD SUCCESSFUL (total time: 8 seconds)

 

please if any one can help i will be very grateful.

Pappi Mcgoo replied on Sat, 2010/06/19 - 8:52pm

Hiya :) i am a bit of a noob :) so bare with me :) i have been writing java serverside script with a flash client i cant seem to call flash functions from java so i have bben looking at other client options. FX looks very promising any pointers suggested for a tutorial ? and can fx be used as a stable client ? in a mvc, view capacity ? thanking you in advance :)

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.