3

以下是我的代码。一切都很好。我可以加载一个远程页面。我可以放置 HTML 内容,但我的img标签显示一个X符号,表示它无法加载图像。

注意:我的图像和类位于同一包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();
            }
        });
    }
}

以下是输出

上述程序的输出

4

3 回答 3

5

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

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

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

于 2014-10-19T14:31:27.050 回答
0

你可以试试这个:

URL url = getClass().getResource("Smiley.png");
File file = new File(url.getPath());
于 2014-10-19T11:40:54.593 回答
0

您可能还需要通过以下方式读取文件路径getClass().getResource()

    for (File fs : f.listFiles()) {
        imgs += "<img src=\"" + getClass().getResource(fs.getName()) + "\" width='50' />";
    }
于 2014-10-19T14:14:07.617 回答