Java Swing - 如何使用pane.getDocument.insert()在JEditorPane中插入圖像
我們想知道如何使用pane.getDocument.insert()在JEditorPane中插入圖像。
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.text.Element;
import javax.swing.text.StyleConstants;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;
public class Main {
public static void main(String[] args) throws Exception {
JFrame frame = new JFrame();
JEditorPane edPane = new JEditorPane();
edPane.setContentType("text/html");
HTMLEditorKit hek = new HTMLEditorKit();
edPane.setEditorKit(hek);
HTMLDocument doc = (HTMLDocument) edPane.getDocument();
doc.insertString(0, "Test testing", null);
Element[] roots = doc.getRootElements();
Element body = null;
for (int i = 0; i < roots[0].getElementCount(); i++) {
Element element = roots[0].getElement(i);
if (element.getAttributes().getAttribute(StyleConstants.NameAttribute) == HTML.Tag.BODY) {
body = element;
break;
}
}
doc.insertAfterEnd(body,"<img src=" + ClassLoader.getSystemResource("thumbnail.png").toString()
+ ">");
frame.add(edPane);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}