How-To's > How do I combine JavaFX and Swing?


Swing objects can be called inside of JavaFX Script code. Most of the standard Swing components such as JButton and JSlider are provided by the javafx.ext.swing package. However, only a subset of all Swing components is supported by this package. For those components that are not provided by javafx.ext.swing package, you can use the JavaFX Swing wrapper class. You might have an existing custom Swing component that you can use in a JavaFX program. For these components, you can use the SwingComponent.wrap() utility function to automatically create a Swing wrapper. After you have added a Swing component to your JavaFX application by using the Swing wrapper, you can apply effects and transitions to that component.

The following code sample demonstrates using the JavaFX Swing wrapper class:

import javafx.stage.Stage;
import javafx.scene.Scene; 
import javax.swing.JTree;
import javafx.ext.swing.SwingComponent; 
import javafx.animation.transition.FadeTransition;

var tree = SwingComponent.wrap(new JTree()); 

tree.translateY = 50;
tree.height = 600;
tree.width = 400;

Stage {
    title: "Add JTree"
    width: 200
    height: 400
    scene: Scene {
         content : tree
        }
        x: 10,
        y: 10
}

var fadeTransition = FadeTransition {
        duration: 3s node: tree
        fromValue: 1.0 toValue: 0.1
        repeatCount:10 autoReverse: true
    }
fadeTransition.play(); 

Mixing JavaFX with the JXMap Viewer Class

With JavaFX Script, you can seamlessly mix existing Swing components, even custom components, with graphics and effects. The example, Mixing Swing Components With JavaFX Graphics, was developed by Josh Marinacci. The example combines the Swing JXMapViewer component from SwingLabs.org with a custom overlay and text in JavaFX graphics. The JXMapViewer class is a complex Swing component from the SwingLabs.org web site. It renders images from tile-based mapping servers such as OpenStreetMap.org in Swing applications, complete with pan and zoom behavior. Because this class already exists, it would be great to use it in JavaFX programs, rather than having to completely rewrite it in a JavaFX Script. Download the sample and examine the code.

Examples

Last Updated: November 2009
[Return to How-To's Home]



Rate This Article
Leave a Comment or Suggest a Topic

Do you have comments about this article? We welcome your participation in our community. Please keep your comments civil and on point. You may optionally provide your email address to be notified of replies—your information is not used for any other purpose. By submitting a comment, you agree to these Terms of Use.

 

English
日本語
한국어
简体中文
русский
Português do Brasil