JavaFX WebView in Java Swing Project

后端 未结 1 1294
北荒
北荒 2020-12-20 06:02

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


        
相关标签:
1条回答
  • 2020-12-20 06:44

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

    0 讨论(0)
提交回复
热议问题