Search code examples
javaswingjtextpane

Adding Image and Text to JTextPane


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?


Solution

  • 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

    Appending the text

    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