Reputation: 23
I have added an image and text using two statements. But in JTextPane, it shows only text. My code given below -
jTextPane1.insertIcon(new ImageIcon("t.png"));
jTextPane1.setText("Technology Wallpaper");
How to add both image and text to the jtextpane?
Upvotes: 1
Views: 1680
Reputation: 347184
setText
will replace the contents of the underlying Document
with the text you pass it. In order to update the text pane, you will need to append the text directly to the 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));
Obviously, if you want insert text before the image, it would be worth noting the current Document
length first and the inserting your new text at that point, after you've inserted the image, depending on your needs
You may also want to take some time and have a look at Using Text Components to get a better understand how the text API works
Upvotes: 1
Reputation: 5463
I suspect that setText
is replacing the whole document. You can use JTextPane#getDocument().insertString()
to add text along with the ICON. Something like follows:
pane.insertIcon(new ImageIcon("logo.png"));
pane.getDocument().insertString(0, "Hello World", null);
Upvotes: 1