javahtmlwebviewjavafxjavafx-webengine

JavaFX: in WebView img tag is not loading local images


Following is my code. Everything is fine. I can load a remote page. I can put HTML content but my img tag shows a X sign meaning that it is not able to load the images.

Note: My images are located in the same package along with the class JavaFX in a folder Smiley and I can list all the images which means there is not problem with the path.

import java.awt.BorderLayout;
import java.io.File;
import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class JavaFX {
    static WebView webView;
    static WebEngine webEngine;
    static String imgs = "";

    public JavaFX() {
        File f = new File(getClass().getResource("/Smiley").getFile());
        for (File fs : f.listFiles()) {
            imgs += "<img src=\""+fs+"\" width='50' />";
        }
        System.out.println(imgs);
    }
    
    private void initAndShowGUI() {
        // This method is invoked on Swing thread
        JFrame frame = new JFrame("FX");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(new BorderLayout()); 
        final JFXPanel fxPanel = new JFXPanel();
        frame.add(fxPanel, BorderLayout.CENTER);
        frame.setVisible(true);
        frame.setSize(800, 800);
        
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                initFX(fxPanel);
            }
        });
    }

    private void initFX(final JFXPanel fxPanel) {
        Group group = new Group();
        Scene scene = new Scene(group);
        fxPanel.setScene(scene);
        webView = new WebView();

        group.getChildren().add(webView);
        webEngine = webView.getEngine();
        webEngine.loadContent("<div id='content'>"+imgs+"</div>");      
    }

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

Following is output

Output of the above program


Solution

  • Thank you guys for your help, I got the Following very simple solution

    imgs += "<img src=\""+fs.toURI()+"\" width='50'>";
    

    the image path must be converted to URI or URL to make the webView able to read it