java webview,Java项目中的JavaFx WebView

i try to use the WebView in my java project, in my code is:

JFXPanel fxPanel = new JFXPanel();

fxPanel.setBounds(10, 48, 439, 362);

desktopPane.add(fxPanel);

WebView webView = new WebView();

fxPanel.setScene(new Scene(webView));

webView.getEngine().load("http://www.stackoverflow.com/");

but the this thown a exception

java.lang.IllegalStateException: Not on FX application thread; currentThread = main

And yes, this is not a JavaFx application.

解决方案

You can embed JavaFX content into a Swing application using JFXPanel. Note that for this to work correctly, you have to be careful to create and access the Swing content on the AWT event dispatch thread, and create and access the JavaFX content on the FX Application Thread, so you will need to carefully manage code using SwingUtilities.invokeLater(...) and Platform.runLater(...). (See the documentation for more details.)

Creating a JFXPanel starts the FX Application toolkit, if it is not already started.

Here is a simple example of embedding a JavaFX WebView into a Swing application:

import java.awt.BorderLayout;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JPanel;

import javax.swing.SwingUtilities;

import javafx.application.Platform;

import javafx.embed.swing.JFXPanel;

import javafx.scene.Scene;

import javafx.scene.web.WebView;

public class FXWebViewInSwing {

private JFXPanel jfxPanel ;

public void createAndShowWindow() {

JFrame frame = new JFrame();

JButton quit = new JButton("Quit");

quit.addActionListener(event -> System.exit(0));

jfxPanel = new JFXPanel();

Platform.runLater(this::createJFXContent);

JPanel buttonPanel = new JPanel();

buttonPanel.add(quit);

frame.add(BorderLayout.CENTER, jfxPanel);

frame.add(BorderLayout.SOUTH, buttonPanel);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setSize(800, 800);

frame.setLocationRelativeTo(null);

frame.setVisible(true);

}

private void createJFXContent() {

WebView webView = new WebView();

webView.getEngine().load("http://stackoverflow.com/questions/42297864/javafx-webview-in-java-project");

Scene scene = new Scene(webView);

jfxPanel.setScene(scene);

}

public static void main(String[] args) {

FXWebViewInSwing swingApp = new FXWebViewInSwing();

SwingUtilities.invokeLater(swingApp::createAndShowWindow);

}

}

Q8wxH.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值