Gia*_*rlo 7 java swing image jeditorpane
我有一个通过这种方式创建的JEditorPane:
JEditorPane pane = new JEditorPane("text/html", "<font face='Arial'>" + my_text_to_show + "<img src='/root/img.gif'/>" + "</font>");
Run Code Online (Sandbox Code Playgroud)
我将此窗格放在JFrame上.
文字显示正确,但我看不到图片,只有一个正方形表示应该有一个图像(即:未找到图片时浏览器显示的"破碎图像")
您必须提供类型,并获取资源.就这样.我测试的例子,但我不确定格式化.希望能帮助到你:
import java.io.IOException;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
public class Test extends JFrame {
public static void main(String[] args) throws Exception {
Test.createAndShowGUI();
}
private static void createAndShowGUI() throws IOException {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("HelloWorldSwing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String imgsrc =
Test.class.getClassLoader().getSystemResource("a.jpg").toString();
frame.getContentPane().add(new JEditorPane("text/html",
"<html><img src='"+imgsrc+"' width=200height=200></img>"));
frame.pack();
frame.setVisible(true);
}
}
Run Code Online (Sandbox Code Playgroud)
JEditorPane 也使用 HTMLDocument.getBase 来定位相对 url,因此,如果您要显示目录中的内容,请确保在 html 文档上设置基址,以便它解析相对于基目录的 url。
根据图像的实际位置,您可能需要扩展 HTMLEditorKit+HTMLFactory+ImageView 并提供 ImageView 的自定义实现,它也负责将属性 URL 映射到图像 URL。