How to add JFXPanel to already existing swing app

China☆狼群 提交于 2019-12-06 15:54:13

JFXPanel extends javax.swing.JComponent so you will add the JFXPanel to the JFrame just as you would with other Swing components: jFrame.getContentPane().add(myJFXPanel)

SSCCE:

package stack;

import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
import javafx.scene.effect.Reflection;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class FXInSwing extends JFrame{

    JFXPanel panel;
    Scene scene;
    StackPane stack;
    Text hello;

    boolean wait = true;

    public FXInSwing(){
        panel = new JFXPanel();
        Platform.runLater(new Runnable(){
            @Override
            public void run() {
                stack = new StackPane();
                scene = new Scene(stack,300,300);
                hello = new Text("Hello");

                scene.setFill(Color.BLACK);
                hello.setFill(Color.WHEAT);
                hello.setEffect(new Reflection());

                panel.setScene(scene);
                stack.getChildren().add(hello);

                wait = false;
            }
        });
        this.getContentPane().add(panel);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setSize(300, 300);
        this.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){
            @Override
            public void run() {
                new FXInSwing();
            }
        });
    }
}  

Remember when you are working with a JFXPanel, you should initialize it on the Swing Event Dispatching Thread but the setScene() should be done on the JavaFX Application Thread. Else, you will get an exception.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!