Skip to content
Advertisement

JavaFX WebView in Java Swing Project

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.

Advertisement

Answer

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);
    }
}

enter image description here

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement