我试图添加一个JFXPanel到我的JFrame。我正在使用Netbeans和Netbeans的Swing GUI Builder。当我运行它时,我没有得到任何错误,JFrame成功创建,但没有出现带有文本的JFXPanel。
下面是我的代码:public class TestingFX {
private static void initJFrame() {
NewJFrame frame = new NewJFrame();
final JFXPanel fxPanel = new JFXPanel();
frame.add(fxPanel);
frame.setVisible(true);
Platform.runLater(new Runnable() {
@Override
public void run() {
fxPanel.setScene(createScene());
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
initJFrame();
}
});
}
public static Scene createScene() {
Text text = new Text("Hello World");
text.setFont(new Font(24));
text.setEffect(new Reflection());
BorderPane pane = new BorderPane();
pane.setCenter(text);
Scene scene = new Scene(pane);
return scene;
}
}
为什么不工作?我做错了什么吗?
也许您应该阅读将JavaFX集成到Swing应用程序中,然后相应地重构您的代码。
试
public class Demo extends Application{
private static JFXPanel javafxPanel;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
initAndShowGUI();
}
});
}
public static void initAndShowGUI() {
JFrame frame = new JFrame("Swing application");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create JavaFX panel.
javafxPanel = new JFXPanel();
frame.getContentPane().add(javafxPanel, BorderLayout.CENTER);
// Create JavaFX scene.
Application.launch (Demo.class, null);
// Show frame.
frame.pack();
frame.setVisible(true);
}
@Override
public void start (Stage mainStage) {
// Add scene to panel
javafxPanel.setScene(createScene());
}
private static Scene createScene() {
Text text = new Text("Hello World");
text.setFont(new Font(24));
text.setEffect(new Reflection());
BorderPane pane = new BorderPane();
pane.setCenter(text);
Scene scene = new Scene(pane);
return scene;
}
}
在创建场景时,本例假定您所包含的代码是有效的。
我试图将JFXPanel添加到JPanel,这为我解决了问题,可能对您也有帮助
jpanel1.setLayout(new FlowLayout());