Following is my code every thing is fine I can load a remote page I can put html content but my img tag shows a X sign means it is not able to load the images.
Note: my images are located in the same package with the class JavaFX
in a folder Smiley and I can list all the images 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();
}
});
}
}
Follwing is output
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
You can try this:
URL url = getClass().getResource("Smiley.png");
File file = new File(url.getPath());
You probably need to read the file paths also via getClass().getResource()
:
for (File fs : f.listFiles()) {
imgs += "<img src=\"" + getClass().getResource(fs.getName()) + "\" width='50' />";
}
来源:https://stackoverflow.com/questions/26447451/javafx-in-webview-img-tag-is-not-loading-local-images