2013-07-20

Putting JavaFX 2 inside a Java Swing application

JavaFX is a set of graphics and media packages that enables developers to design, create, test, debug, and deploy rich client applications that operate consistently across diverse platforms. JavaFX 2.2 and later releases are fully integrated with the Java SE 7 Runtime Environment (JRE) and the Java Development Kit (JDK). Because the JDK is available for all major desktop platforms (Windows, Mac OS X, and Linux), JavaFX applications compiled to JDK 7 and later also run on all the major desktop platforms.

The integration between Java 7 and JavaFX 2 now makes it possible to actually use JavaFX within a Java Swing application. This is especially useful if you want to create a video player using the JavaFX media classes, but want to using a Swing container for it because the other portions of your code (e.g. network, web service API calls) are all done using Java. Or, its just plain tedious to refactor your entire Java Swing application.

With the JavaFX 2.x JFXPanel class, you can host JavaFX components
within a Swing JPanel:
JPanel [-- JFXPanel [-- Scene [-- Group [-- javafx.control.*

In code it will be something like:

JPanel pnl = new JPanel();
JFXPanel jfxPanel = new JFXPanel();
// Create the JavaFX Scene
createFX();
pnl.add(jfxPanel);

....

// The FX Scene needs to be created on "FX user thread",
// and NOT on the AWT Event Thread
private void createFX() {
    PlatformImpl.startup(
        new Runnable() {
            public void run() {
                Group g = new Group();
                Scene s = new Scene(g, 80, 20);
                SizeView sv = new SizeView();
                g.getChildren().add(sv);
                jfxPanel.setScene(s);
            }
        });
}

The Java Tutorial for Swing FX interop is here
http://docs.oracle.com/javafx/2/swing/swing-fx-interoperability.htm

For creation of of the media player using the embedded Java FX classes, I will address this in a later post. Do look through the Java Tutorial for a more complete sample code (download it).

No comments:

Post a Comment

Github CoPilot Alternatives (VSCode extensions)

https://www.tabnine.com/blog/github-copilot-alternatives/