问题描述
这是我在这里的第一个问题,所以我有点紧张,但让我们直接说清楚.我正在尝试在 JFrame
中嵌入 JavaFX
场景,但似乎不太成功.场景有时可以正确渲染,但其他时候只是灰色背景.最近几天,我一直在努力寻找解决方案,但似乎找不到.这是代码:
This is my first question here so I'm a bit nervous, but let's get straight to the point. I'm trying to embed a JavaFX
scene in a JFrame
and I don't seem to quite succeed. The scene sometimes renders properly, but other times it's just grey background. I've been trying to think of a solution for the last couple days, but I just can't seem to find one. Here's the code:
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);
});
});
});
}
我不确定为什么,但是在取消注释我注释掉的代码段的同时,似乎更可能使场景正确渲染.我为我的英语不好而道歉,这不是我的母语.
I'm not sure why, but while uncommenting the piece of code that I commented out seems to make it much more likely for the scene to render properly.I apologies for my bad English, it's not my native language.
推荐答案
以下是在Swing JFrame
中具有JavaFX组件的示例:
Here is the example which has JavaFX components in a Swing JFrame
:
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);
}
}
这篇关于在Swing中嵌入JavaFX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!