如果从Java程序中调用JavaFX,没有办法结束JavaFX的主线程,只能执行一次,多次从Java中调用JavaFX,会报主线程只能有一个。
所以,我们可以用Java自带的图形化界面Swing,通过Swing去调用JavaFX
// 引入JavaFX的jar包
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-controls</artifactId>
<version>17.0.2</version>
</dependency>
上代码
public class javaTest {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
initAndShowGUI();
}
});
}
private static void initAndShowGUI() {
JFrame frame = new JFrame("Swing and JavaFX");
final JFXPanel fxPanel = new JFXPanel();
frame.add(fxPanel);
frame.setSize(300,200);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Platform.runLater(new Runnable(){
@Override
public void run() {
try {
initFx(fxPanel);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
});
}
private static void initFx(JFXPanel fxPanel) throws IOException {
Scene scene = createScene();
fxPanel.setScene(scene);
}
private static Scene createScene() throws FileNotFoundException {
Group root = new Group();
Scene scene = new Scene(root, Color.ALICEBLUE);
// Swing调用JavaFX中的WebView组件
WebView browser = new WebView();
WebEngine webEngine = browser.getEngine();
webEngine.load("file:///D:/JavaFX.html");
root.getChildren().add(browser);
return scene;
}
}