【问题标题】:Embedding JavaFX in Swing在 Swing 中嵌入 JavaFX
【发布时间】:2018-08-16 05:23:15
【问题描述】:

这是我在这里的第一个问题,所以我有点紧张,但让我们直奔主题。我正在尝试在JFrame 中嵌入JavaFX 场景,但我似乎不太成功。场景有时会正确渲染,但有时只是灰色背景。在过去的几天里,我一直在想一个解决方案,但我似乎无法找到一个解决方案。代码如下:

public class Popup {
public Popup() {
    SwingUtilities.invokeLater(() -> {
        JFrame frame = new JFrame("popup");
        frame.setUndecorated(true);
        frame.setType(Window.Type.POPUP);
        JFXPanel panel = new JFXPanel();
        frame.add(panel);
        Platform.runLater(() -> {
            VBox root = new VBox();
            root.setStyle("-fx-background: red;");
            Scene scene = new Scene(root);
            Label label = new Label("hello friend");
            Label other = new Label("hello WORLD!!!");
            root.getChildren().addAll(label, other);
            panel.setScene(scene);
            /*synchronized (this) {
                try {
                    wait(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }*/

            SwingUtilities.invokeLater(() -> {
                frame.pack();
                frame.setVisible(true);
            });
        });
    });
}

我不知道为什么,但是取消注释我注释掉的那段代码似乎使场景更有可能正确渲染。 我很抱歉我的英语不好,这不是我的母语。

【问题讨论】:

  • 我有你的代码十几次没有问题,你使用的是什么版本的Java?
  • 我使用的是 java 8
  • 我正在使用 10 - 可能值得更新
  • 我在运行您的代码时注意到了这一点:场景有时会正确渲染,但其他时候只是灰色背景。试试我发布的代码,看看它是否适合你。

标签: java swing javafx


【解决方案1】:

这是在 Swing JFrame 中包含 JavaFX 组件的示例:

import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
import javax.swing.*;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import java.awt.Point;
public class FxInSwing {
    private JFrame frame;
    public static void main(String... args) {
        SwingUtilities.invokeLater(() -> {
            new FxInSwing().initAndShowGUI();
        });
    }
    /*
     * Builds and displays the JFrame with the JFXPanel.
     * This method is invoked on the Swing Event Dispatch Thread -
     * see the main().
     */
    private void initAndShowGUI() {
        frame = new JFrame("JavaFX in Swing App");
        JFXPanel fxPanel = new JFXPanel();
        frame.add(fxPanel);
        frame.setSize(400, 200);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setLocation(new Point(150, 150));
        Platform.runLater(() -> {
            fxPanel.setScene(createScene());
        });
    }
    private Scene createScene() {
        VBox root = new VBox();
        root.setStyle("-fx-background: red;");
        Label label = new Label("hello friend");
        Label other = new Label("hello WORLD!!!");
        root.getChildren().addAll(label, other);
        return new Scene(root);
    }
}

【讨论】:

    猜你喜欢
    • 2013-12-23
    • 2013-05-29
    • 2021-10-08
    • 1970-01-01
    • 2012-12-24
    • 2012-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多