我使用两个语句添加了图像和文本。但是在 JTextPane 中,它只显示文本。我在下面给出的代码 -
jTextPane1.insertIcon(new ImageIcon("t.png"));
jTextPane1.setText("Technology Wallpaper");
如何将图像和文本都添加到 jtextpane?
我怀疑这setText
是替换整个文档。您可以使用JTextPane#getDocument().insertString()
与 ICON 一起添加文本。如下所示:
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
首先注意当前长度,然后在插入图像之后插入新文本,具体取决于您的需要
您可能还想花一些时间看看使用文本组件以更好地了解文本 API 的工作原理