How to add images in JTextPane?

11,388

Solution 1

There is an easy way to add an image:

JTextPane pane = new JTextPane ();
pane.insertIcon ( new ImageIcon ( "/path/to/image.png" ) );

But there is no simple way to copy an image from the pane, since it cannot be selected and cannot be easily located in the pane document.

Solution 2

You need a StyledDocument, like resulting from HTML. Hence set the content type to "text/html". Then <img src="file:..."> will link to an image on the file system.

Then you can provide drag-and-drop or paste from File or Image (the latter you have to save in your own files).

Share:
11,388
Suhail Ahamed
Author by

Suhail Ahamed

Updated on June 20, 2022

Comments

  • Suhail Ahamed
    Suhail Ahamed almost 2 years

    I want to give the user the facility to copy and paste Images in JTextPane. Please help me.

  • JFreeman
    JFreeman over 5 years
    For my own uses I found that this works even better: pane.insertComponent( new JLabel(myIcon) )