将图像和文本添加到 JTextPane

Adding Image and Text to JTextPane

我使用两个语句添加了图像和文本。但在 JTextPane 中,它只显示文本。我的代码如下 -

jTextPane1.insertIcon(new ImageIcon("t.png"));
jTextPane1.setText("Technology Wallpaper");

如何将图像和文本同时添加到 jtextpane 中?

我怀疑 setText 正在替换整个文档。您可以使用 JTextPane#getDocument().insertString() 添加文本和图标。如下所示:

    pane.insertIcon(new ImageIcon("logo.png"));
    pane.getDocument().insertString(0, "Hello World", null);

setText 会将底层 Document 的内容替换为您传递给它的文本。为了更新文本窗格,您需要将文本直接附加到文档中

JTextPane tp = new JTextPane();
tp.insertIcon(new ImageIcon("mySuperAwesomePictureSomewhere.jpg"));
try {
    Document doc = tp.getDocument();
    doc.insertString(doc.getLength(), "\nTruer words were never spoken", null);
} catch (BadLocationException ex) {
    ex.printStackTrace();
}
add(new JScrollPane(tp));

显然,如果您想在图像之前插入文本,请先注意当前的 Document 长度,然后在插入图像后插入新文本,具体取决于您的需求

您可能还想花点时间看看 Using Text Components 以更好地理解文本 API 的工作原理