gpt4 book ai didi

java - JFXPanel setScene 使用 Java 11 卡住

转载 作者:可可西里 更新时间:2023-11-01 09:57:25 24 4
gpt4 key购买 nike

我想将 openjfx 集成到我的 Java 11 代码中。在 Windows 10 上使用 IntelliJ IDEA 2018.2.6,我创建了一个测试项目并尝试了以下代码

import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
import javafx.scene.control.TabPane;

public class Java11FXTestApplication {



public static void main(String[] args) {
JFXPanel dummyPanel;
TabPane dummyTabPane;
Scene dummyScene;
System.out.println("Creating JFX Panel");
dummyPanel = new JFXPanel();
System.out.println("Creating TabPane");
dummyTabPane = new TabPane();
System.out.println("Creating Scene");
dummyScene = new Scene(dummyTabPane);
System.out.println("Setting Scene");
dummyPanel.setScene(dummyScene); //Freezing here
System.out.println("Scene Created");
}
}

此代码在 setScene() 方法调用中卡住。我尝试调试它,发现代码在 JFXPanel.setScene 方法中的 secondaryLoop.enter() 调用中无限期等待。知道为什么吗?

This code works fine in JDK-8 but not working with java-11.0.1.

我对这个问题毫无进展,有点卡在 Java11 JavaFX 问题上。代码有问题吗?或 java11 的 javafx 报告的任何问题

最佳答案

您正在主线程上设置场景。来自 JFXPanel 的文档(强调我的):

There are some restrictions related to JFXPanel. As a Swing component, it should only be accessed from the event dispatch thread, except the setScene(javafx.scene.Scene) method, which can be called either on the event dispatch thread or on the JavaFX application thread.

Platform.runLater 调用(或 SwingUtilities.invokeLater)中包装 setScene

Platform.runLater(() -> {
dummyPanel.setScene(dummyScene);
System.out.println("Scene Created");
});

请注意,对于您当前的代码,一旦 main 返回,JVM 将继续运行。创建一个 JFXPanel 会初始化 JavaFX 运行时,它不会退出,直到最后一个窗口关闭(仅当 Platform.isImplicitExittrue 时)或 Platform.exit 被调用。由于您的代码不执行任何操作,因此 JavaFX 运行时将继续运行。


JFXPanel 的文档还给出了一个如何使用它的示例(请注意,几乎所有事情都发生在事件调度线程JavaFX 应用程序线程上):

Here is a typical pattern how JFXPanel can used:

 public class Test {

private static void initAndShowGUI() {
// This method is invoked on Swing thread
JFrame frame = new JFrame("FX");
final JFXPanel fxPanel = new JFXPanel();
frame.add(fxPanel);
frame.setVisible(true);

Platform.runLater(new Runnable() {
@Override
public void run() {
initFX(fxPanel);
}
});
}

private static void initFX(JFXPanel fxPanel) {
// This method is invoked on JavaFX thread
Scene scene = createScene();
fxPanel.setScene(scene);
}

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

关于java - JFXPanel setScene 使用 Java 11 卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53343167/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com