2014-10-19 68 views
0

以下是我的代码,每件事情都很好我可以加载一个远程页面我可以把HTML内容,但我的img标签显示一个X标志,意味着它无法加载图像。JavaFX:在WebView中img标签没有加载本地图像

注:我的图片都位于同一个封装类JavaFX文件夹中的笑脸,我可以列出所有的图像是指没有与路径

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问题是输出

Output of the above program

回答

1

谢谢你们的帮助,我得到了以下非常简单的解决方案

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

图像路径必须被转换以URI或URL使webView能够读取它

0

你可以试试这个:

URL url = getClass().getResource("Smiley.png"); 
File file = new File(url.getPath()); 
+1

解释如何使用代码,为什么这可能是一个解决方案的问题 – 2014-10-19 12:11:02

+0

@Sanket Pipariya感谢您的答复问题不在路径正确的路径中,我可以列出目录中的所有文件,但它不会在使用img标签的WebView中呈现! – Muhammad 2014-10-19 12:12:31

+0

亲爱的@RuneFS和Sanket Pipariya我解决了这个问题在这里看到http://stackoverflow.com/a/26451542/1966247 – Muhammad 2014-10-19 14:35:24

0

你可能需要通过getClass().getResource()读取文件路径也:

for (File fs : f.listFiles()) { 
     imgs += "<img src=\"" + getClass().getResource(fs.getName()) + "\" width='50' />"; 
    } 
+0

感谢亲爱的你的帮助:),我解决了这个问题请看这里http://stackoverflow.com/a /1966247分之26451542 – Muhammad 2014-10-19 14:33:42

相关问题